【发布时间】: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*太模糊了)。 -
@πάνταῥεῖ,如果引用在线程占用的时间内变得悬空,则可能会出现问题,因此在使用引用时必须像往常一样小心。我没有听说任何其他问题。