我的應用程序分爲一些較小的域,爲了減少它們之間的依賴關係,我將使用上下文對象。讓我們考慮一個簡單的例子:上下文對象的同步
class SomeType1;
class SomeType2;
class dummy;
//context for first domain
class foo
{
public:
virtual void setPtr1 (SomeType1* val) = 0;
virtual SomeType2* getPtr2() = 0;
static foo* getCTX()
{
//statement bellow is a singleton which creates one instance of dummy and
//returns its address as foo*
return AppCTX::AccessorType<dummy>::getCTX<foo>();
}
virtual ~foo();
};
//context for second domain
class bar
{
public:
virtual void setPtr2 (SomeType2* val) = 0;
virtual SomeType1* getPtr1() = 0;
static bar* getCTX()
{
//same as above but casts dummy* to bar*
return AppCTX::AccessorType<dummy>::getCTX<bar>();
}
virtual ~bar();
};
//dummy is a singleton created in AppCTX::AccessorType<dummy>
class dummy: public foo, public bar
{
public:
virtual void setPtr1 (SomeType1* val)
{
ptr1 = val;
}
virtual SomeType1* getPtr1()
{
return ptr1;
}
virtual void setPtr2 (SomeType2* val)
{
ptr2 = val;
}
virtual SomeType2* getPtr2()
{
return ptr2;
}
virtual ~dummy();
private:
SomeType1* ptr1;
SomeType2* ptr2;
};
我的域開始其使用範圍內也是如此PTR1和PTR2可以並行訪問多個線程。我是否需要使用互斥鎖同步setPtrs和getPtrs?有沒有可能ptr1和ptr2以某種方式被破壞?