std :: thread()和std :: ref()以及PIMPL:C ++ 11线程语义

时间:2015-06-15 23:45:22

标签: c++11 stdthread pimpl-idiom

下面我提供了我遇到的情况的伪代码。我有两个资源需要在一个线程上创建,另一个需要在主线程上创建。但是,第一个资源ResourceA必须在创建ResourceB之后重新创建,但ResourceA必须在创建ResourceB之前“准备好”(如果您对更多详细信息感兴趣,请参阅注释部分。)

我的确切问题是:

  1. 提供的ResourceA和ResourceB由指向结构的成员指针所拥有,该结构将在两个单独的线程上进行修改。在将不可复制的父对象传递给std :: thread时,是否必须使用std :: ref。
  2. 如果我执行两个用例之间的语义差异(将其作为指针传递或使用std :: ref()?
  3. 由于在第二个线程上创建ResourceB和ResourceB之后必须重新创建ResourceA,如果我不使用std :: ref(),主线程上的ResourceA会看到对ResourceB所做的更改吗?
  4. 有问题的课程将被定义为:

    class Foo : public non_copyable // You can still move
    {
    private:
        struct FooImpl;
        FooImpl *m_foo;
        void Run();
    
    public:
        Foo();
        ~Foo();
        bool Init();
    };
    

    在Foo.cpp内部,我们有以下定义:

    struct Foo::FooImpl
    {
        ResourceA ra;
        ResourceB rb;
    };
    
    Foo::Foo() :
        m_foo(new FooImpl())
    {}
    
    Foo::~Foo()
    {
        delete m_foo;
    }
    
    void Foo::Run()
    {
        [Create Resource B in an advanced state needed to recreate A]
    
        [Notify condition on main thread so Resource B can be recreated]
    
        [Conditionally wait for A to be recreated on main thread]
    
        [Do stuff with B and this]
    }    
    
    bool Foo::Init()
    {
        [Create Resource A in Preparation for Resource B this must be done on this thread]
    
        std::thread t(std::bind(&Foo::Run, this)); // Note here I am not passing 
                                                   // by std::ref. This is the line in
                                                   // question
    
        [Conditionally wait for Resource B to be created on thread t]
    
        [Recreate Resource A now that B has been created]
    
        [Notify condition on thread t that A has been recreated]
    
        [Handle A stuff and do stuff with this]
    }
    

0 个答案:

没有答案