C++ c++;pthread_创建返回值
我正在尝试按顺序遍历二叉树的多线程处理。由于pthread_create,我收到错误C++ c++;pthread_创建返回值,c++,multithreading,C++,Multithreading,我正在尝试按顺序遍历二叉树的多线程处理。由于pthread_create,我收到错误 #include <iostream> #include <pthread.h> #include <list> using namespace std; static pthread_t threads[9]; static int count=0; struct node { int val
#include <iostream>
#include <pthread.h>
#include <list>
using namespace std;
static pthread_t threads[9];
static int count=0;
struct node
{
int value=0;
node *left=NULL;
node *right=NULL;
};
list<int> inordertraversal(node* n)
{
list<int> l1,l2;
if(n->left!=NULL)
list<int> l1=pthread_create(&threads[count++],NULL,inordertraversal,n->left);
if(n->right!=NULL)
list<int> l2=pthread_create(&threads[count++],NULL,inordertraversal,n->right);
list<int> l;
l.insert(l.begin(),l1.begin(),l1.end());
l.push_back(n->value);
l.insert(l.end()--,l2.begin(),l2.end());
return l;
}
struct node* newNode(int data)
{
node* node;
node->value=data;
node->left=NULL;
node->right=NULL;
return node;
}
int main()
{
struct node *root=newNode(7);
root->left=newNode(9);
root->right=newNode(5);
root->left->left=newNode(13);
root->left->right=newNode(17);
root->right->left=newNode(56);
root->right->right=newNode(21);
root->left->left->left=newNode(45);
root->right->left->right=newNode(45);
root->left->left->right=newNode(67);
list<int> l=inordertraversal(root);
for(list<int>::iterator it=l.begin();it!=l.end();it++)
{
cout<<*it<<" ";
}
}
#包括
#包括
#包括
使用名称空间std;
静态pthread_t线程[9];
静态整数计数=0;
结构节点
{
int值=0;
node*left=NULL;
node*right=NULL;
};
OrderTraversal中的列表(节点*n)
{
列表l1、l2;
如果(n->left!=NULL)
列表l1=pthread_create(&threads[count++],NULL,inordertraversal,n->left);
如果(n->right!=NULL)
list l2=pthread_create(&threads[count++],NULL,inordertraversal,n->right);
清单l;
l、 插入(l.begin(),l1.begin(),l1.end());
l、 推回(n->值);
l、 插入(l.end()--,l2.begin(),l2.end());
返回l;
}
结构节点*新节点(整型数据)
{
节点*节点;
节点->值=数据;
节点->左=空;
节点->右=空;
返回节点;
}
int main()
{
结构节点*root=newNode(7);
根->左=新节点(9);
根->右=新节点(5);
根->左->左=新节点(13);
根->左->右=新节点(17);
根->右->左=新节点(56);
根->右->右=新节点(21);
根->左->左->左=新节点(45);
根->右->左->右=新节点(45);
根->左->左->右=新节点(67);
列表l=inordertraversal(根目录);
for(list::iterator it=l.begin();it!=l.end();it++)
{
cout您误解了pthread\u create
的功能。它只是创建线程并返回线程创建的状态(是否正常或失败)。它根本不处理线程中运行的函数返回的内容。事实上,线程函数可能根本不应该返回结果。它可能应该更新所有线程都可以访问的某个公共变量(此时需要互斥或其他互斥机制).pthread线程函数必须符合库指定的函数定义:
int pthread_create(pthread_t*, const pthread_attr_t*, void* ()(void), void*)
因此,OrderTraversal(node*n)
中的函数list不符合void*()(void)
您必须将函数签名更改为符合上述签名的函数,然后递归调用该函数
void* inorder(void)
{
pthread_create(&threads[count++],NULL,wrapper,(void *)n->left);
}
将列表l;
作为类成员,这样您就不需要在每次函数调用中传递它。pthread\u create需要一个函数指针,该指针的类型应为void*()(void*)。
您的函数具有返回类型列表。或线程拥有的变量或结构,只有在线程连接后才由父级读取。