pthread_join 中的“状态”到底代表什么以及如何查询它

cel*_*vek 3 c c++ pthreads

我想知道 pthread_join 中的“status”参数到底是用来做什么的

int pthread_join(pthread_t thread, void **status);
Run Code Online (Sandbox Code Playgroud)

我正在尝试利用它,但我无法理解它到底代表什么。根据文档

地位

Is the location where the exit status of the joined thread is stored.
Run Code Online (Sandbox Code Playgroud)

如果不需要退出状态,可以将其设置为 NULL。

好的。听起来不错。我该如何使用它?我看过一些例子,但我无法掌握它的窍门(有些例子在使用它时是完全错误的)。所以我确实去了源头。在 glibc 实现中,我发现了以下 pthread_join 测试:

...
pthread_t mh = (pthread_t) arg;
void *result;
...
if (pthread_join (mh, &result) != 0)
{
  puts ("join failed");
  exit (1);
}

here follows the WTF moment ...

if (result != (void *) 42l)
{
  printf ("result wrong: expected %p, got %p\n", (void *) 42, result);
  exit (1);
}
Run Code Online (Sandbox Code Playgroud)

所以结果(这是一个地址)的值应该是42?这是图书馆级别的全球性问题吗,因为我在测试中找不到任何具体内容?

编辑:看来这个问题提供了与我所问内容相关的信息

Mar*_*ork 5

状态设置为线程开始执行的函数返回的值(如果线程提前退出,则设置为传递给 pthread_exit() 的值)。

例子:

 void* thread_func(void* data)
 {
     if (fail())
     {
         pthread_exit((void*)new int(2)); // pointer to int(2) returned to status
     }
     return (void*)new int(1); // pointer to int(1) returned to status;

     // Note: I am not advocating this is a good idea.
     //       Just trying to explain what happens.
 }

 pthread_create(&thread, NULL, thread_func, NULL);

 void*  status;
 pthread_join(thread, &status);
 int*   st = (int*)status;

 // Here status is a pointer to memory returned from thread_func()
 if ((*st) == 1)
 {
      // It worked.
 }
 if ((*st) == 2)
 {
      // It Failed.
 }
Run Code Online (Sandbox Code Playgroud)