c - 在主线程上调用 pthread_join 是否有效?

标签 c pthreads posix

这段代码的行为是否定义明确?

#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/

相关文章:

我们可以在其他头文件中执行线程吗?

compiler-construction - 启动期间生成的 ELF 可执行段错误

c - 当 DPI 设置为 150% 时关闭 Aero (Windows 7),全屏窗口仅覆盖任务栏

c++ - Cmake可以生成一个同时支持调试和发布的makefile吗

c - 多维数组和传输缓冲区

php - 如何在 Apache2 服务器上启用线程安全

c - 线程加工

linux - 如何使用带引号的字段(可能包含分隔符)对 CSV 进行排序

c - 来自 mips 路由器上的 clock_gettime() 的纳秒

javascript - 将 OpenGL 程序从 C 移植到 WebGL 和 Javascript