pthreads - Correctly waiting for a thread to terminate in C -
this code plays sound clip creating thread it. when bleep() runs, sets global variable bleep_playing true. in main loop, if notices bleep_playing has been set false, terminates loop, cleans (closing files, freeing buffers), , exits. don't know correct way wait detached thread finish. pthread_join() doesn't job. while loop here continually checks bleep_id see if it's valid. when isn't, execution continues. correct , portable way tell thread clean , terminate before next thread allowed 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
hmm... pthread_join
should job. far remember thread has call pthread_exit
...?
/* bleep thread */ void *bleep(void *) { /* bleeping */ pthread_exit(null); } /* main thread */ if (pthread_create(&thread, ..., bleep, ...) == 0) { /* ** try sleeping ms !!! ** i've had issues on multi core cpus requiring sleep ** in order created thread "exist"... */ pthread_join(&thread, null); }
anyway if isn't doing thing shouldn't poll global variable since eat cpu. instead create mutex (pthread_mutex_*
-functions) locked , freed "bleep thread". in main thread can wait mutex makes thread sleep until "bleep thread" frees mutex.
(or quick & , dirty: sleep small amount of time while waiting bleep_playing becoming false)
Comments
Post a Comment