将派生类指针的向量传递给线程

时间:2016-06-08 13:33:21

标签: c++ multithreading pointers vector

我有一个带有Derived1和Derived2派生类的基类和一个Consumer类。

我想创建一个带有两个派生类对象的Base指针向量,然后传递给使用者类,以便它可以使用

获取派生类的详细信息
pointervec.at(0).i

我多年来一直坚持这一点,无法让它发挥作用。这是我所拥有的简化版本。我关注创建向量的语法,将其传递给线程并访问不同的索引。

#include<vector>
#include<thread>
#include<iostream>

using namespace std;

class Base
{
public:
    Base() {};
    void dosomething() {cout<<i<<endl;}
    int i;
};

class Derived1 : public Base
{
public:
    Derived1() {i = 5;}
};

class Derived2 : public Base
{
public:
    Derived2() {i = 10;}
};

class Consumer
{
public:
    Consumer();
    void dostuff( vector<Base> &pointervec) {cout<<5<<endl;}
};

int main( int argc, char ** argv )
{
    Derived1 derived1;
    Derived2 derived2;

    vector<Base*>pointervec;
    pointervec.push_back(&derived1);
    pointervec.push_back(&derived2);

    std::thread t1(&Derived1::dosomething, &derived1);
    std::thread t2(&Derived2::dosomething, &derived2);
    std::thread t3(&Consumer::dostuff, ref(pointervec));

    t1.join();
    t2.join();
    t3.join();
}

1 个答案:

答案 0 :(得分:4)

为了让你的例子有用,有一些错误需要纠正。

  1. 由于Consumer::doStuff是非静态成员函数,因此您需要Consumer的实例来运行它。
  2. 由于上述原因,Consumer需要定义的构造函数
  3. doStuff的签名需要Base指针的引用(引用a),而不是Base个对象
  4. 线程t3需要将Consumer的实例作为其第一个转发参数(以提供this参数。
  5. 最终工作代码:

    #include<vector>
    #include<thread>
    #include<iostream>
    
    using namespace std;
    
    class Base
    {
    public:
        Base() {};
        void dosomething() {cout<<i<<endl;}
        int i;
    };
    
    class Derived1 : public Base
    {
    public:
        Derived1() {i = 5;}
    };
    
    class Derived2 : public Base
    {
    public:
        Derived2() {i = 10;}
    };
    
    class Consumer
    {
    public:
        Consumer() {}
        void dostuff( vector<Base*> &pointervec) {cout<<pointervec.at(0)->i<<endl;}
    };
    
    int main( int argc, char ** argv )
    {
        Derived1 derived1;
        Derived2 derived2;
    
        Consumer c;
        vector<Base*>pointervec;
        pointervec.push_back(&derived1);
        pointervec.push_back(&derived2);
    
        std::thread t1(&Derived1::dosomething, &derived1);
        std::thread t2(&Derived2::dosomething, &derived2);
        std::thread t3(&Consumer::dostuff, &c, ref(pointervec));
    
        t1.join();
        t2.join();
        t3.join();
    }