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

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

int pthread_join(pthread_t thread, void **status); 

我正在尝试使用它,但我无法理解它究竟代表什么。 根据文件

状态

 Is the location where the exit status of the joined thread is stored. 

如果不需要退出状态,则可以将其设置为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); } 

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

编辑:似乎这个问题提供了与我问的相关的信息

状态设置为线程开始执行的函数返回的值(如果线程提前退出,则从传递给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. } 

阅读pthread_create的文档。 运行线程的函数定义为返回void* 。 无论它返回什么, pthread_join通过void** ‘传递给你。 如果函数选择返回(void *)42 ,那么’42’就是你得到的。