什么是“状态”在pthread_join中表示和如何查询它 [英] What does exactly the "status" in pthread_join represent and how to query it

查看:301
本文介绍了什么是“状态”在pthread_join中表示和如何查询它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道pthread_join中的status参数是什么。

I'm wondering what exactly the "status" parameter in the pthread_join is for

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

我试图使用它,但我不明白它是什么代表。
根据文件

I'm trying to make use of it but I cannot understand what exactly does it represent. According to the documentation


status

status

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

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

This can be set to NULL if the exit status is not required.

好的。听起来不错。我如何使用它?我看了一些例子,但我不能
得到它的悬念(和一些例子是使用它是完全错误的)。所以我去了
源。在glibc实现中,我发现了对pthread_join的以下测试:

OK. That sounds nice. How do I use it? I've looked at some examples but I cannot get the hang of it(and some examples are plain wrong in using it). So I did go to the source. In the glibc implementation I found the following test for 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? ?这是全局的
在库级别,因为我找不到任何具体的 test

So the value of the result(which is an address) should be 42?? Is this something global at the library level, because I could not find anything specific in the test?

编辑:看起来此问题提供的信息与我提出的问题相关

it seems this question provides info related to what I asked

推荐答案

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

The status is set to the value returned by the function that the thread starts executing (or from the value passed to pthread_exit() if the thread exits early).

示例:

 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_join中表示和如何查询它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆