C++ interrupt thread waiting for user-input

I have a problem, where I need to interrupt and wait for input. Any idea how to do this?

bool run;
void partReceive() {
    while(run) {
        ...
        int rect_len = (int) recvfrom(servSockFD, buffer, 
              MAX_MESSAGE_LEN, 0, (struct sockaddr*) &newAddr, &slen);
        ...
    }
}

void partCount() {
    int i = 0;
    while(run) {
        i++;
        if (i >= 5) {
            run = false;
        }
    }
 }

 int main() {
       run = true;
       thread receive(partReceive);
       thread count(partCount);
       count.join();
       receive.join();
       return 0;
 }

This won't work, because partReceive() will hold until it receives input from socket..

Upvotes: 1

Views: 646

Answers (2)

Erik Alapää
Erik Alapää

Reputation: 2703

In addition to the existing answer, note that a useful design pattern is to use a pipe (or more precisely, a socketpair()), where main thread owns one end and the 'select thread' owns the other end. Then, to stop the 'select thread', you can send one character on the pipe (assuming the descriptor has been added to select). This wakes up the thread that should be terminated (thread sleeps in select until something happens on the socket or on the control pipe).

Upvotes: 2

Werner Henze
Werner Henze

Reputation: 16726

As suggested in the man page of recvfrom:

You need to change receiver to first call select (see man page) to check if there is something to read. If there is something to read you can recvfrom knowing that it now will not block. select can also timeout if nothing is to be read. In that case you can at least check if you shall end the receiver thread.

Upvotes: 0

Related Questions