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:
BAD - create suitable member (
a) downcast from IA to A (or from IB to B respectively), and use it b) make it static, and callcritical_section m_cs;
) of either A or B, andA::m_cs
(orB::m_cs
)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
}
精彩评论