在C ++中面向对象设计中声明共享变量的位置?

时间:2018-06-19 08:17:51

标签: c++ multithreading oop

class B
{
    // This will run in the thread
    void run();
};

class A
{
    // This will run in the thread
    void run();
};

class Thread_manager
{
    A objA;
    B objB;

    // This class will start the threads.
};

共享变量是struct的向量。

一种方法是使其全球化。我想根据OOP知道在C ++中面向对象设计中应该在哪里声明共享变量?

2 个答案:

答案 0 :(得分:2)

与所有变量一样,您应该在最窄的范围内声明共享变量,这些变量具有初始化它们的数据以及它们所需的生命周期。

缺少任何其他上下文,合理的默认值为

class B
{
    SharedData & shared;

public:
    B(SharedData & shared) : shared(shared) {}
    void run();
};

class A
{
    SharedData & shared;

public:
    A(SharedData & shared) : shared(shared) {}
    void run();
};

class Thread_manager
{
    SharedData shared;
    A objA;
    B objB;
    std::thread threadA;
    std::thread threadB;

public:
    Thread_manager() 
     : objA(shared), 
       objB(shared), 
       threadA(&A::run, &objA), 
       threadB(&B::run, &objB)
    {}

    ~Thread_manager()
    {
        threadA.join();
        threadB.join();
    }
};

答案 1 :(得分:0)

选择太多了。如果您通过ThreadManager管理线程,则其实例可能是共享状态的好地方。例如:

struct SharedState {
   std::vector<int> v;
};

class A { 
   public: 
      void run(SharedState* state) { std::cout << state->v.size() << std::endl; }
};

class ThreadManager {
   public:
      ThreadManager() : state_(new SharedState{}) { state_->v.resize(10); }

      void run_threads() {
         threads_.emplace_back(&A::run, &a_, state_.get());
      }

      void finish_threads() {
         for (auto & t : threads_) t.join();
      }

   private:
      std::unique_ptr<SharedState> state_;
      std::vector<std::thread> threads_;
      A a_;
};

int main() {
   ThreadManager tm;
   tm.run_threads();
   tm.finish_threads();
}