这段代码的行为是否定义明确?
#include <stdio.h>
#include <pthread.h>
pthread_t mt;
void *start(void *x)
{
void *y;
pthread_join(mt, &y);
printf("joined main thread\n");
return 0;
}
int main()
{
pthread_t t;
mt = pthread_self();
pthread_create(&t, 0, start, 0);
pthread_exit(0);
}
Run Code Online (Sandbox Code Playgroud)
是的,这是可能的.实际上,这种可能性是pthread_detach()存在的主要原因之一.从POSIX文档中可以pthread_detach()看到(参见参考资料man pthread_detach):
It has been suggested that a "detach" function is not necessary; the
detachstate thread creation attribute is sufficient, since a thread
need never be dynamically detached. However, need arises in at least
two cases:
1. In a cancellation handler for a pthread_join() it is nearly essen-
tial to have a pthread_detach() function in order to detach the
thread on which pthread_join() was waiting. Without it, it would
be necessary to have the handler do another pthread_join() to
attempt to detach the thread, which would both delay the cancella-
tion processing for an unbounded period and introduce a new call
to pthread_join(), which might itself need a cancellation handler.
A dynamic detach is nearly essential in this case.
2. In order to detach the "initial thread" (as may be desirable in
processes that set up server threads).
Run Code Online (Sandbox Code Playgroud)
所以根据标准,你提出的建议是好的.
编辑:只是为了进一步确认,状态的POSIX描述exec():
新进程映像中的初始线程应该是可连接的,就像使用detachstate属性设置为PTHREAD_CREATE_JOINABLE一样创建的.