Frotz
Frotz

Reputation: 592

Correctly waiting for a thread to terminate in C

This code plays a sound clip by creating a thread to do it. When bleep() runs, it sets the global variable bleep_playing to TRUE. In its main loop, if it notices that bleep_playing has been set to FALSE, it terminates that loop, cleans up (closing files, freeing buffers), and exits. I don't know the correct way to wait for a detached thread to finish. pthread_join() doesn't do the job. The while loop here continually checks bleep_id to see if it's valid. When it isn't, execution continues. Is this the correct and portable way to tell a thread to clean up and terminate before the next thread is allowed to be created?

    if (bleep_playing) {
        bleep_playing = FALSE;
        while (pthread_kill(bleep_id, 0) == 0) {
            /* nothing */
        }
    }
    err = pthread_create(&bleep_id, &attr, (void *) &bleep, &effect);

I

Upvotes: 0

Views: 239

Answers (1)

Lukas Thomsen
Lukas Thomsen

Reputation: 3207

Hmm... pthread_join should do the job. As far as I remember the thread has to call pthread_exit...?

/* bleep thread */
void *bleep(void *)
{
    /* do bleeping */

    pthread_exit(NULL);
}


/* main thread */ 
if (pthread_create(&thread, ..., bleep, ...) == 0)
{
    /*
    **  Try sleeping for some ms !!!
    **  I've had some issues on multi core CPUs requiring a sleep
    **  in order for the created thread to really "exist"...
    */

    pthread_join(&thread, NULL);
}

Anyway if it isn't doing its thing you shouldn't poll a global variable since it will eat up your CPU. Instead create a mutex (pthread_mutex_*-functions) which is initially locked and freed by the "bleep thread". In your main thread you can wait for that mutex which makes your thread sleep until the "bleep thread" frees the mutex.

(or quick & and dirty: sleep for a small amount of time while waiting for bleep_playing becoming FALSE)

Upvotes: 1

Related Questions