[英]How do you pass in structs in multiple threads using C++?
最近,我一直在创建一个使用结构创建多个线程的程序。 在我的子程序中,我注意到我的结构中的值从未被传递(它们是随机的东西)。 我被告知用创建的每个线程实例化一个新结构,但这对我不起作用(可能是因为语法)。
我正在寻找一种方法来进行小的更改,以便在创建线程时将结构中的值传递到子例程中。
结构:
struct Node {
long int upper_bound;
long int lower_bound;
int sum = 0;
};
在主要:
struct Node *node;
创建线程:
node -> upper_bound = interval;
node -> lower_bound = min;
for( int i = 0; i < num_threads; i++ ) {
ids[i] = i;
cout << "Making a thread with these boundaries: " << node -> lower_bound << " " << node -> upper_bound << endl;
rc = pthread_create(&thrdid[i],NULL,sub,(void *) &node);
node -> lower_bound += (interval+1);
node -> upper_bound += interval;
//make a new thread, but where?
}
在子程序中:
void* sub(void *arg) {
int i;
i = *( (int *)arg );
Node* aNode = static_cast<Node*>(arg);
......
}
我究竟做错了什么? 为什么我的值没有被传入?
您必须为每个线程创建Node
实例。
可以这样做:
node = new Node; // create an instance of Node
node -> upper_bound = interval;
node -> lower_bound = min;
for( int i = 0; i < num_threads; i++ ) {
ids[i] = i;
cout << "Making a thread with these boundaries: " << node -> lower_bound << " " << node -> upper_bound << endl;
rc = pthread_create(&thrdid[i],NULL,sub,(void *) node); // pass pointers to Node instead of pointers to pointers
struct Node *next_node = new Node; // create next instance of Node
next_node -> lower_bound = node -> lower_bound + (interval+1);
next_node -> upper_bound = node -> upper_bound + interval;
node = next_node;
}
另一种方法是一次为所有线程分配Node
:
std::vector<Node> nodes(num_threads);
node[0].upper_bound = interval;
node[0].lower_bound = min;
for( int i = 0; i < num_threads; i++ ) {
ids[i] = i;
cout << "Making a thread with these boundaries: " << node -> lower_bound << " " << node -> upper_bound << endl;
rc = pthread_create(&thrdid[i],NULL,sub,(void *) &nodes[i]);
if (i + 1 < num_threads) {
nodes[i + 1].lower_bound = nodes[i].lower_bound + (interval+1);
nodes[i + 1].upper_bound = nodes[i].upper_bound + interval;
}
}
您之前将 node 声明为指针
struct Node *node;
然后在 pthread_create 中获取它的地址:
rc = pthread_create(&thrdid[i],NULL,sub,(void *) &node);
这导致将指针传递给指针。 而只是使用:
rc = pthread_create(&thrdid[i],NULL,sub,(void *) node);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.