开发者

How to share single critical section between two classes

I have some trouble finding the right design solution for a problem of sharing same critical section object between two classes in different class hierarchies.

Imagine:

class IB;
class IA { 
    public: void method_one(); 
};
class A : public IA { 
    IB* m_ib; 
};

class IB { 
    public: void method_two(); 
};
class B : public IB { 
    IA* m_ia; 
};

Now, the calls to method_one() and method_two() should be synchronized. I happen to use critical_section object for synchronization, but wonder how should I do it.

I managed to figure out some ideas:

  1. BAD - create suitable member (critical_section m_cs;) of either A or B, and

    a) downcast from IA to A (or from IB to B respectively), and use it

    b) make it static, and call A::m_cs (or B::m_cs)

  2. BETTER - create additional singletonish object/struct that would manage critical_section object and provide an access to it:

    class CriticalSectionProvider {
        //(...)
    public: 
        static critical_section& GetIt() { static critical_section cs; return cs; }
    }
    

Unfortunately, I am not happy with any of these an开发者_Python百科d think that someone may have better idea.

How to share single critical section between two classes in this case?


The simplest approach is : create an instance of critical_section in the main(), before creating any threads between which you want to share the object.

Pass it to the constructors of the classes and store it as reference:

class A : public IA { 
    IB* m_ib; 
    critical_section & m_cs; //reference
    public:
           A(critical_section & cs) : m_cs(cs) {}
};

class B : public IB { 
    IA* m_ia; 
    critical_section & m_cs; //reference
    public:
           B(critical_section & cs) : m_cs(cs) {}
};

int main()
{
    critical_section cs = /*create it*/;

    A a = cs; //call the constructor, passing the reference
    B b = cs; //call the constructor, passing the reference
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜