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

Return Type Pthread Create Using C++

本文关键字:创建 C++ 使用 Pthread 返回类型      更新时间:2023-10-16

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

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)

可以传递给CCD_ 1。

现在,为了从这个函数返回指向某个东西的指针,您需要两个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);
}

返回一个堆分配的指针,指向[所以使用new来分配它]您的新对象(在线程中分配,稍后可能在加入它的"父"线程中释放,即使用结果)。