If available, I would use the select function with a timeout in the loop to achieve this functionality.
as suggested by Glenn
The select function with a timeout value will wait for the socket to connect for a specified period of time. If a socket tries to connect, it can be accepted during this period. By cycling this choice with a timeout, you can test new connections until the interrupt condition is met.
Here is an example:
std::atomic<bool> stopThread; void theThread ( std::atomic<bool> & quit ) { struct timeval tv; int activity; ... while(!quit) { // reset the time value for select timeout tv.tv_sec = 0; tv.tv_usec = 1000000; ... //wait for an activity on one of the sockets activity = select( max_sd + 1 , &readfds , NULL , NULL , &tv); if ((activity < 0) && (errno!=EINTR)) { printf("select error"); } if (FD_ISSET(master_socket, &readfds)) { if ((new_socket = accept(master_socket, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) { perror("accept"); exit(EXIT_FAILURE); } ... } } int main(int argc, char** argv) { ... stopThread = false; std::thread foo(theThread, std::ref(stopThread)); ... stopThread = true; foo.join(); return 0;
}
A More Complete Select Example http://www.binarytides.com
I'm new to C ++, so I'm sure my code and answer can be improved.
source share