c++ - 返回类型 Pthread 使用 C++ 创建

标签 c++ multithreading pthreads

我正在尝试创建一个返回特定类型对象的函数。问题是创建线程不接受它。有人可以帮我编写以下代码吗?

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/

相关文章:

c++ - 创建线程时有多少开销?

multithreading - POSIX 线程堆栈内存 - 我们可以有不同的堆栈大小和安全问题吗?

python,如何增量创建线程

c++ - 将 LookAt 相机旋转一定角度

C++如何使用指针循环移位数组元素

Javadoc 文档就地呈现。可以在 IDE 中看到 pretty-print 文档吗?

c# - 客户端-服务器拍卖系统。控制台模式

C# 如何在非静态成员函数上调用 Action?

c++ - cond_broadcast 和调度顺序

c++ - 检查整个 vector 是否为零