【问题标题】:How do you pass in structs in multiple threads using C++?如何使用 C++ 在多个线程中传递结构?
【发布时间】: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 会更容易做到这一点,因为您不必为投射东西而烦恼。

标签: c++ pthreads


【解决方案1】:

您必须为每个线程创建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;
            }
}

【讨论】:

  • 所以我有很多。我只是没有创建一个新实例并传递值。这更有意义。谢谢你。
【解决方案2】:

您之前将节点声明为指针

struct Node *node;

然后在 pthread_create 中获取它的地址:

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

这导致将指针传递给指针。而是使用:

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

【讨论】:

  • 那是我没有看到的。感谢您指出这一点
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-01
  • 1970-01-01
  • 2017-04-14
  • 1970-01-01
  • 2011-01-22
相关资源
最近更新 更多