C++ 如何使用C++;?

C++ 如何使用C++;?,c++,pthreads,C++,Pthreads,最近,我一直在创建一个程序,该程序使用结构创建多个线程。在我的子程序中,我注意到我的结构中的值从未被传递(它们是随机的)。我被告知要用创建的每个线程实例化一个新的结构,但这对我不起作用(可能是因为语法) 我正在寻找一种方法来进行一个小的更改,以便在创建线程时将来自struct的值传递到子例程中 结构: struct Node { long int upper_bound; long int lower_bound; int sum = 0; }; 大体上: struct

最近,我一直在创建一个程序,该程序使用结构创建多个线程。在我的子程序中,我注意到我的结构中的值从未被传递(它们是随机的)。我被告知要用创建的每个线程实例化一个新的结构,但这对我不起作用(可能是因为语法)

我正在寻找一种方法来进行一个小的更改,以便在创建线程时将来自struct的值传递到子例程中

结构:

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?
}
节点->上限=间隔;
节点->下限=min;
对于(inti=0;icout您必须为每个线程创建
节点的实例

可以这样做:

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;
}

您以前将节点声明为指针

struct Node *node;
然后在pthread_create中获取它的地址:

rc = pthread_create(&thrdid[i],NULL,sub,(void *) &node);
这导致将指针传递给指针。只需使用:

rc = pthread_create(&thrdid[i],NULL,sub,(void *) node);

我会尝试一下,但我主要想了解如何确保使用我拥有的来传递结构,你会发现这样做更容易,因为你不必乱扔东西。所以我有很多。我只是没有创建一个新实例并传递值。这更有意义。谢谢你。这很简单我没看到。谢谢你指出这一点
rc = pthread_create(&thrdid[i],NULL,sub,(void *) &node);
rc = pthread_create(&thrdid[i],NULL,sub,(void *) node);