代码之家  ›  专栏  ›  技术社区  ›  R.. GitHub STOP HELPING ICE

在主线程上调用pthread_join有效吗?

  •  7
  • R.. GitHub STOP HELPING ICE  · 技术社区  · 14 年前

    此代码的行为是否定义良好?

    #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);
    }
    
    3 回复  |  直到 14 年前
        1
  •  8
  •   psmears Touffy    8 年前

    是的,这是可能的。事实上,这种可能性是 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).
    

    所以根据标准你的提议是很好的。

    编辑: 只是为了进一步确认 POSIX description of exec() 国家:

    新进程中的初始线程 图像应该是可连接的,就像创建的一样 detachstate属性设置为 PTHREAD_CREATE_可连接。

        2
  •  0
  •   Will    14 年前

    我无法想象为什么你会在现实世界的应用程序中这样做(有人请评论一个例子,如果你能想到的话),但我甚至不相信这是可能的。所有关于pthreads的搜索,我看到的总是从主线程调用连接,而不是从辅助线程。

    连接还要求尝试连接的线程是用PTHREAD_CREATE_JOINABLE标志创建的。我找不到任何说明主线程是否是这样创建的文档。

    代码专家也有类似的问题 here 可能有助于也可能没有助于澄清。

    如果要完成的是在主线程退出后继续的子线程,则应该创建子线程分离或使用。 fork / vfork 相反,这取决于你在哪个平台上。

        3
  •  0
  •   Jens Gustedt    14 年前

    你的做法在我看来正式有效,特别是因为你正在 pthread_exit 结束时 main .

    另一方面,我在POSIX中没有发现任何迹象表明 主要的 是否可以合并。psmears回答的理由只是 主要的 应该是可分离的,因为它是可连接的。

    还有一些恶意的东西 pthread_detach 由main或so调用的子例程。所以你应该明确地检查 pthread_join 去查查这样的案子。

    同样在您的示例代码中,在创建 start 以及终止 主要的 :

    • 主要的 可能在之前终止 开始 到达 pthread_连接

    对访问的互斥 mt 变量应该能解决这个问题。