Sleeping in a Thread (C / POSIX Threads)

Emre Yazici picture Emre Yazici · Oct 25, 2010 · Viewed 24.9k times · Source

I am developing a multithreaded application that makes use of POSIX Threads. I am using threads for doing a periodical job and for that purpose I am using usleep(3) to suspend thread execution. My question is how can I cancel usleep() timer from the main thread, I tried pthread_kill(thread, SIGALRM) but it has a global effect which results in termination of the main application (by default). Here is my pseudo code:

void threaded_task(void *ptr) {
    initialize();

    while(running) {
        do_the_work();
        usleep(some_interval);
    }

    clean_up();
    release_resources();
}

And here is the pseudo function that is used to stop (and gracefully shutdown) given thread from the main thread:

void stop_thread(pthread_t thread) {
    set_running_state(thread, 0); // Actually I use mutex staff
    // TODO: Cancel sleep timer so that I will not wait for nothing.
    // Wait for task to finish possibly running work and clean up 
    pthread_join(thread, NULL);
}

What is the convenient way to achieve my goal? Do I have to use conditional variables or can I do this using sleep() variants?

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · Oct 25, 2010

USe select() with a FIFO or socket that you can poke in order to wake it up.