2 i amking I_amKing 于 2014.12.20 12:43 提问

单例模式,为保证线程安全,采用临界区对象,为何访问无效? 3C

#include
#include

class Singleton
{
public:
static Singleton *GetInstance()
{
if (m_Instance == NULL )
{
//Lock(); // C++没有直接的Lock操作,请使用其它库的Lock,比如Boost,此处仅为了说明
EnterCriticalSection(&g_cs); //为什么Access Violation
if (m_Instance == NULL )
{
m_Instance = new Singleton ();
}
LeaveCriticalSection(&g_cs);
//UnLock(); // C++没有直接的Lock操作,请使用其它库的Lock,比如Boost,此处仅为了说明
}
return m_Instance;
}

static void DestoryInstance()
{
    if (m_Instance != NULL )
    {
        delete m_Instance;
        m_Instance = NULL ;
    }
    DeleteCriticalSection(&g_cs);
}

int GetTest()
{
    return m_Test;
}

private:
Singleton(){ m_Test = 0;InitializeCriticalSection(&g_cs); }
static Singleton *m_Instance;
static CRITICAL_SECTION g_cs;
int m_Test;
};

Singleton* Singleton :: m_Instance = NULL;
CRITICAL_SECTION Singleton:: g_cs;
int main(int argc , char *argv [])
{
Singleton *singletonObj = Singleton ::GetInstance();
cout<GetTest()<<endl;
Singleton ::DestoryInstance();
return 0;
}

4个回答

bdmh
bdmh   Ds   Rxr 2014.12.20 15:37

你好像没有::InitializeCriticalSection(&g_cs);

bdmh
bdmh   Ds   Rxr 2014.12.20 15:38

看多了,那你的无效是什么概念

zilaishuichina
zilaishuichina   Rxr 2014.12.22 10:59

InitializeCriticalSection(&g_cs)的时机不对

你的g_cs的初始化在Singleton()构造函数里面,

而这个构造函数在锁中间,

EnterCriticalSection(&g_cs); //为什么Access Violation
if (m_Instance == NULL )
{
m_Instance = new Singleton ();  //此处才会调用Singleton()构造函数,才会初始化g_cs,因此上面的EnterCriticalSection是无效的
}
LeaveCriticalSection(&g_cs); 
zilaishuichina
zilaishuichina   Rxr 2014.12.22 11:01
Csdn user default icon
上传中...
上传图片
插入图片