What if a being-waited thread detaches itself?

拟墨画扇 提交于 2020-01-15 06:57:26

问题


#include <pthread.h>

void thread_routine(void*)
{
    sleep(5);
    pthread_detach(pthread_self());
    sleep(5);
}

int main()
{
    pthread_t t;
    pthread_create(&t, 0, thread_routine, 0);
    pthread_join(t);
}

Will pthread_join(t); return immediately after pthread_detach(pthread_self()); succeed?


回答1:


The behavior is undefined, and thus obviously to be avoided at all costs.

(As far as I can tell the behavior is implicitly undefined. There are several kindred instances of explicitly undefined behavior in the spec, but this exact scenario is not mentioned.)

For the curious, on an NPTL Linux system near me, both the pthread_detach() and the pthread_join() return 0, and, moreover, the latter blocks and successfully gets the value returned by the thread. On an OS X system near me, by contrast, the pthread_detach() succeeds, and the pthread_join() immediately fails with ESRCH.




回答2:


Your code is buggy. By the time you call pthread_join, the thread may already have terminated. Since it's detached, the pthread_t is not longer valid. So your code may pass an invalid pthread_t to pthread_join, which can cause unpredictable behavior.

To avoid these kinds of problems one specific thing should control the lifetime of a thread. That can be the thread itself, if it's detached, in which case no thread should try to join it. It can also be the thread that joins it, in which case the thread should not be detached.



来源:https://stackoverflow.com/questions/27262926/what-if-a-being-waited-thread-detaches-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!