【问题标题】:pthread_create(), how do I get the returned value from the passed functionpthread_create(),如何从传递的函数中获取返回值
【发布时间】:2014-07-25 03:15:47
【问题描述】:

如何获取我通过 pthread_create 的函数返回的 void 指针?

static void* pthread_sendRequest(void* name){
    RequestChannel chan(*(string*) name, RequestChannel::CLIENT_SIDE);
    string returnValue = chan.send_request("Hi");
    return (void*) &returnValue;

}

pthread_create(thread, NULL, pthread_sendRequest, new string(&"worker #" [i]));

当 pthread_sendRequest 传递给 pthread_create 时,如何获取它的返回值,以便将其转换回字符串指针并获取实际字符串?

pthread_join(thread, void**) 中的 void** 是否为我抓取了它?

【问题讨论】:

  • 线程函数中并没有像returned value 这样的东西。如果需要在线程之间交换数据,使用线程函数的参数。
  • 如果 start_routine 返回,效果就像是隐式调用了 pthread_exit(),使用 start_routine 的返回值作为退出状态。 - pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_create.html。此外,由于这是 C++,std::thread t{func, std::ref(returnedData)}; 并让 func 返回 void 并通过引用获取要返回的任何数据。
  • @chris IIRC 试图 return 使用此机制(例如分配的字符串等)的任何 real 值,除了常量错误指示符引用之外,没有效果不好。我不太确定,但我不会使用这个功能(我认为这主要是因为void* 太模糊了)。
  • @πάνταῥεῖ,如果引用在线程占用的时间内变得悬空,则可能会出现问题,因此在使用引用时必须像往常一样小心。我没有听说任何其他问题。

标签: c++ unix pthreads posix


【解决方案1】:

正如其他答案所表明的,从线程函数返回的值可以通过传递一个指向缓冲区的指针来获取该返回值。

但是,在您的示例中,您的线程函数返回一个指向非静态局部变量的指针,这是无效的(无论函数是否在线程中执行),因为一旦函数退出,本地对象不再存在.

你也许可以这样做:

static void* pthread_sendRequest(void* name){
    RequestChannel chan(*(string*) name, RequestChannel::CLIENT_SIDE);
    string* returnValue = new string(chan.send_request("Hi"));
    return (void*) returnValue;

}

pthread_create(thread, NULL, pthread_sendRequest, new string(&"worker #" [i]));

// ...

void* temp = NULL;
pthread_join(*thread, &temp); 

string* returnValue = (string*) temp;

// when done with returnValue
delete returnValue;

【讨论】:

    【解决方案2】:

    当您调用pthread_join 时,它需要一个指向void* 的指针,该返回值将复制到其中。 (从该页面链接的示例说明了用法,但无论如何都很明显)。

    【讨论】:

    • 您新发布的代码证明了一个完全不同的问题——我不会费心去介绍它,因为 Michael Burr 已经很友好地这样做了。干杯。
    【解决方案3】:

    如果返回func,或者调用pthread_exit,可以在pthread_join中获取退出状态

    int pthread_join(pthread_t tid, void **thread_return);
    

    tidpthread_create填写的标识符。

    【讨论】:

    • thread_return 是否与单独调用 func 函数时返回的指针相同?
    • @NoorThabit 我没有关注你的问题,该参数由pthread_join 的调用者填充,如果线程退出,将填充退出状态。
    • @NoorThabit: 如果func 调用pthread_exit(my_thread_ptr)(通过编码return my_void_ptr; 显式或隐式调用),那么就是将被复制到*thread_return 中的值. (在支持线程取消的系统上,当加入已取消的线程时,PTHREAD_CANCELED 等标记可能会被复制到 *thread_return 中。
    • @TonyD 我更新了问题。对不起,我不是很清楚。
    • @YuHao 再看问题,我更新了。非常感谢!
    猜你喜欢
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多