c++ 单例模式

1 一个类只有一个实例:一般创建实例的代码可能会涉及到线程安全方面的问题,需注意,代码如下:
 2 #include <iostream> 
 3 using namespace std;
 4 #define HUNGRY_MODE // 饿汉模式,在一开始就创建
 5 #define LAZY_MODE // 懒汉模式,在需要的时候才创建
 6 class DSingletonMode{
 7  private:
 8   static DSingletonMode *m_pSingletonInstance;
 9  private:
10   DSingletonMode(){ /* Constructor */}
11   DSingletonMode(const DSingletonMode &other){
12    // Copy constructor
13   }
14   DSingletonMode operator = (const DSingletonMode &other){
15    // Assignment constructor
16   }
17  public:
18   // Get singleton mode object, and it can have parameters
19   static DSingletonMode *GetSingletonInstance(void){
20    /*
21    These code has thread self question
22     */
23    #ifdef LAZY_MODE
24    Lock();
25    if (NULL == m_pSingletonInstance)
26    {
27     /* code */
28     m_pSingletonInstance = new DSingletonMode();
29    }
30    unlock();
31    #endif
32    
33    return (m_pSingletonInstance);
34   }
35   void OtherFunction(/* Parameters */){
36    // Do something
37    cout<<"I can do anything!"<<endl;
38   }
39 }
40 #ifdef HUNGRY_MODE
41 static DSingletonMode *DSingletonMode::m_pSingletonInstance = new DSingletonMode();
42 #else
43 static DSingletonMode *DSingletonMode::m_pSingletonInstance = NULL;
44 #endif

对于上述编译可能存在错误,因为类的静态变量需要放在源文件而不是头文件进行显式的初始化;

还有对于懒汉模式可能存在线程安全问题,所以对于创建单例那里需要进行上锁设置,对于windows可以采用临界区,可用如下代码代替:

// 添加类的私有成员
private:
    CCriticalSection m_section; 

// 改写返回实例的函数
static DSingletonMode *GetSingletonInstance(void){
            /*
            These code has thread self question
             */
            #ifdef LAZY_MODE
            // Lock(); 实现线程安全(realize thread safe)
            m_section.Lock(0);
            if (NULL == m_pSingletonInstance)
            {
                /* code */
                m_pSingletonInstance = new DSingletonMode();
            }
            // unlock();
            m_section.Unlock();
            #endif

            return (m_pSingletonInstance);
        }

临界区可以对某段代码进行加锁,直到释放权限。

以后会进行改进!
原文链接: https://www.cnblogs.com/dhf-0214/p/3511129.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/117921

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月10日 下午4:43
下一篇 2023年2月10日 下午4:58

相关推荐