gpt4 book ai didi

c++ - pthread_create(),如何从传递的函数中获取返回值

转载 作者:行者123 更新时间:2023-11-30 01:52:14 24 4
gpt4 key购买 nike

如何获取传递给 pthread_create 的函数的返回空指针?

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** 是否帮我抓取它?

最佳答案

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

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

你也许可以这样做:

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;

关于c++ - pthread_create(),如何从传递的函数中获取返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24947446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com