【发布时间】:2020-10-02 22:51:38
【问题描述】:
最近,我一直在创建一个使用结构创建多个线程的程序。在我的子例程中,我注意到我的结构中的值从未传递(它们是随机的东西)。我被告知要在创建每个线程时实例化一个新结构,但这对我不起作用(可能是因为语法)。
我正在寻找一种方法来进行一些小的更改,以便在创建线程时将结构中的值传递到子例程中。
结构:
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);
......
}
我做错了什么?为什么我的值没有被传入?
【问题讨论】:
-
我会尝试,但我主要想了解如何确保使用我拥有的结构实际传递结构,
-
您会发现使用
std::thread会更容易做到这一点,因为您不必为投射东西而烦恼。