如何获取我传递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_sendRequest的返回值,所以我可以将它转换回字符串指针并获取实际字符串?
pthread_join(thread,void **)中的void **是否适合我?
答案 0 :(得分:2)
正如其他答案所示,可以通过传入指向缓冲区的指针来捕获线程函数返回的值,以获取返回的值。
但是,在您的示例中,您的线程函数返回一个指向非静态局部变量的指针,该变量无效(函数是否在线程中执行),因为一旦函数退出本地对象不再存在
你可能会做类似的事情:
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;
答案 1 :(得分:1)
当你调用pthread_join时,它需要一个指向void*
的指针,其中复制了该返回值。 (从该页面链接的示例说明了用法,但无论如何它都非常明显。)
答案 2 :(得分:1)
如果返回func
或致电pthread_exit
,您可以在pthread_join
int pthread_join(pthread_t tid, void **thread_return);
tid
是pthread_create
填写的标识符。