正确等待线程在 C 中终止

Correctly waiting for a thread to terminate in C

此代码通过创建线程来播放声音片段。当 bleep() 运行时,它将全局变量 bleep_playing 设置为 TRUE。在它的主循环中,如果它注意到 bleep_playing 已被设置为 FALSE,它就会终止该循环、清理(关闭文件、释放缓冲区)并退出。我不知道等待分离线程完成的正确方法。 pthread_join() 不做这项工作。这里的 while 循环不断检查 bleep_id 以查看它是否有效。如果不是,则继续执行。这是告诉线程在允许创建下一个线程之前清理和终止的正确且可移植的方法吗?

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

嗯...pthread_join 应该做的工作。据我记得线程必须调用 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);
}

无论如何,如果它没有做它的事情,你不应该轮询一个全局变量,因为它会吃掉你的 CPU。相反,创建一个互斥量(pthread_mutex_*-函数),它最初由 "bleep thread" 锁定和释放。在您的主线程中,您可以等待使您的线程休眠的互斥锁,直到 "bleep thread" 释放互斥锁。

(或快速且肮脏:在等待 bleep_playing 变为 FALSE 时休眠一小段时间)