我正在尝试创建一个返回特定类型对象的函数。问题是创建线程不接受它。有人可以帮我编写以下代码吗?
struct thread_args
{
Key *k;
QNode *q;
uint8_t USED_DIMENSION;
};
QLeafNode *st ;
struct thread_args Structthread2;
Structthread1.k=min;
Structthread1.q=start;
Structthread1.USED_DIMENSION=4 ;
pthread_create( &thread1, NULL,(void*)&FindLeafNode, ((void *) &Structthread1));
pthread_join( thread1, (void**)st);
QLeafNode* FindLeafNode (Key *k, QNode * r, uint8_t USED_DIMENSION ){
}
最佳答案
首先,您的线程函数定义不正确。只有形式的功能:
void* function_name(void* param)
可以传递给pthread_create
。
现在,为了从此函数返回指向某物的指针,您需要两个 pthread 函数:
pthread_exit(void *value_ptr);
在线程函数内部调用这个通过value_ptr
和
pthread_join(pthread_t thread, void **value_ptr);
在父线程中调用此方法以等待具有句柄 thread
的子线程终止,并在 value_ptr
中检索 pthread_exit
返回的值.
所以你的代码应该是这样的:
struct thread_args
{
Key *k;
QNode *q;
uint8_t USED_DIMENSION;
};
QLeafNode *st ;
struct thread_args Structthread1;
Structthread1.k=min;
Structthread1.q=start;
Structthread1.USED_DIMENSION=4 ;
pthread_create(&thread1, NULL, FindLeafNode, ((void *) &Structthread1));
pthread_join(thread1, (void**)st);
...
void* FindLeafNode (void* param) {
struct thread_args* value = (struct thread_args*) param;
// use value for computations
QLeafNode* result = ... // allocate result with new / malloc
pthread_exit((void*)result);
}
关于c++ - 返回类型 Pthread 使用 C++ 创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9776405/