Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sleeping in a Thread (C / POSIX Threads)

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?

like image 595
Emre Yazici Avatar asked Oct 25 '10 16:10

Emre Yazici


1 Answers

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

like image 70
Ignacio Vazquez-Abrams Avatar answered Sep 27 '22 19:09

Ignacio Vazquez-Abrams