pthread在线程函数和取消处理程序中加入子线程?

时间:2017-04-09 13:39:55

标签: multithreading unix pthreads pthread-join

我遇到了以下带有并发问题的场景,使用pthread库实现:

我有一个可能随时取消的帖子。当该线程被取消时,它需要取消其子线程,并确保其子线程在终止之前已被取消。

所以我最终在子线程上调用pthread_join两次,一次在线程例程中(就像线程未被取消时,我需要那个结果),一次在线程的取消清理处理程序中。

但是,pthread_join不允许两次加入同一个线程,那么会发生什么?

以下是伪代码:

void CleanupFunc(void* ChildThread)
{
    pthread_cancel(*(pthread_t*)ChildThread);
    pthread_join(*(pthread_t*)ChildThread, NULL);
}

void* ThreadFunc(void* _)
{
    pthread_t ChildThread;
    pthread_cleanup_push(&CleanupFunc, &ChildThread);
    pthread_create(&ChildThread, NULL, &ChildThreadFunc, NULL);
    pthread_join(ChildThread, NULL);
    pthread_cleanup_pop(0);
}

提前致谢!

1 个答案:

答案 0 :(得分:0)

  

但是,pthread_join不允许两次加入同一个线程,那么会发生什么?

线程不再可连接,因此结果是未定义的行为。

根据POSIX standard documentation for pthread_join()

  

如果thread指定的值,则行为未定义   pthread_join()的参数不引用可连接的线程。

相关问题