最近,我一直在创建一个使用structs创建多个线程的程序。在我的子程序中,我注意到我的结构中的值从未被传递(它们是随机的(。我被告知要用创建的每个线程实例化一个新的结构,但这对我来说不起作用(可能是因为语法原因(。
我正在寻找一种方法来进行一个小的更改,以便在创建线程时将结构中的值传递到子例程中。
结构:
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;
}
}
您之前将节点声明为指针
struct Node *node;
然后在pthread_create:中获取它的地址
rc = pthread_create(&thrdid[i],NULL,sub,(void *) &node);
这导致将指针传递给指针。相反,只需使用:
rc = pthread_create(&thrdid[i],NULL,sub,(void *) node);