2012-03-19 51 views
0

我想创建一个函数,它返回某个类型的对象。问题是创建线程不接受它。有人可以帮我用下面的代码吗?返回类型Pthread使用C++创建

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){ 

} 
+0

关键代码是不是在这里。 Structthread1是如何声明的? – bmargulies 2012-03-19 19:17:39

+0

“创建线程不接受”是什么意思?你是否收到编译错误?碰撞? – 2012-03-19 19:18:20

+1

如果我不得不猜测,它是在'FindLeafNode'上投射的'void *'。 (也奇怪的期望,代码将做一些合理的时候,有3个参数的函数接收一个) – Hasturkun 2012-03-19 19:21:54

回答

3

首先,您的线程函数没有正确定义。只有以下形式的功能:

void* function_name(void* param) 

可以传递给pthread_create。现在

,以指针从这个函数返回的东西,你需要两个并行线程功能:

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); 
} 
+0

从技术上讲,我相信你应该通过'&FindLeafNode'而不是'FindLeafNode'。 – Hurkyl 2012-03-19 20:06:09

+0

@Hurkyl:据我所知。我最近实际上使用了pthreads,它只用FindLeafNode。 – Tudor 2012-03-19 20:08:58

+0

不错的工作人员一个更多的错误goooooo – 2012-03-19 20:20:26

0

返回一个堆分配指针[所以使用new分配它]新对象(分配在线程,或许在“父”以后被释放螺纹接合它,即,使用该结果)。

+0

问题是,它并没有为pthread_create编译:(( – 2012-03-19 19:19:14

+0

)编译它(哪个系统,哪个编译器,哪个编译器选项),你编译了什么确切的源代码,以及你得到了什么确切的错误信息? – 2012-03-19 19:30:27

+0

QuadTree.cc:332:错误:ISO C++禁止采用非限定或带括号的非静态成员函数的地址来形成指向成员函数的指针。假设'&QuadTree :: FindLeafNode' – 2012-03-19 19:40:08