这段代码的行为是否定义明确?
#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);
}
最佳答案
是的,这是可能的。事实上,这种可能性是 pthread_detach()
存在的主要原因之一。来自 pthread_detach()
的 POSIX 文档(参见 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).
所以根据标准,您提出的建议是可以的。
编辑:进一步确认,POSIX description of exec()
状态:
The initial thread in the new process image shall be joinable, as if created with the detachstate attribute set to PTHREAD_CREATE_JOINABLE.
关于c - 在主线程上调用 pthread_join 是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4228203/