How to properly handle signals when using the worker thread pattern?

Posted by ipartola on Stack Overflow See other posts from Stack Overflow or by ipartola
Published on 2010-05-18T11:54:47Z Indexed on 2010/05/18 12:00 UTC
Read the original article Hit count: 229

Filed under:
|
|

I have a simple server that looks something like this:

void *run_thread(void *arg) {
    // Communicate via a blocking socket
}

int main() {
    // Initialization happens here...

    // Main event loop
    while (1) {
        new_client = accept(socket, ...);
        pthread_create(&thread, NULL, &run_thread, *thread_data*);
        pthread_detach(thread);
    }

    // Do cleanup stuff:
    close(socket);
    // Wait for existing threads to finish
    exit(0); 
)

Thus when a SIGINT or SIGTERM is received I need to break out of the main event loop to get to the clean up code. Moreover most likely the master thread is waiting on the accept() call so it's not able to check some other variable to see if it should break;.

Most of the advice I found was along the lines of this: http://devcry.blogspot.com/2009/05/pthreads-and-unix-signals.html (creating a special signal handling thread to catch all the signals and do processing on those). However, it's the processing portion that I can't really wrap my head around: how can I possibly tell the main thread to return from the accept() call and check on an external variable to see if it should break;?

© Stack Overflow or respective owner

Related posts about c

    Related posts about pthreads