class SelfTesting
{
private:
char * pChar;
SelfTesting()
{
pChar = new char[1024 * 1024 * 1024];
}
public:
static SelfTesting * pSelf;
static SelfTesting& GetInst()
{
if (!pSelf)
{
boost::lock_guard<boost::mutex> lock(g_boost_mutex);
if (!pSelf)
{
pSelf = new SelfTesting;
}
}
return *pSelf;
}
};
Generally, I know the problem is caused by:
1. allocate memory for `SelfTesting`
2. store the pointer to the allocated memory in `pChar`
3. initialize `SelfTesting`
- If other thread touch the pointer between step 2 and 3, data race condition happens. From
- If the pointer copying is not atomic, data race condition can also happens. From
I know that I can use local static variable to implement this pattern in C++11. My question is that is the above implementation thread safe or it is undefined when I am using C++ standard before C++11. Is boost::mutex
make sure that pSelf
will update after lock
is died?