C++单利模式常见问题

本文探讨了C++中单例模式的常见问题,强调了线程安全的重要性。通过代码示例对比了不同单例实现方式的差异,包括线程不安全的写法和推荐的线程安全实现。文中指出,构造函数的原子性是确保单例安全的关键,并建议将单例获取函数写在cpp文件中以避免多线程环境下的错误和内存泄漏。

C++语言是一门具有面向对象的高性能语言,其执行效率不小于C语言的80%。所以在现在的深度学习中被广泛使用,深度学习在跑的实例需要大量的计算资源,算法在实现上又要实现模型的抽象。综合考虑,C++是其载体的不二之选,模型验证可以使用更加方便的python等高级语言,方便修改和编写简单。实际在工程中使用的还是以C++作为模型的载体来实现算法。

C++是一门结合高性能和具有面向对象抽象的语言,同比其他语言具有这么多的优点,为什么其他语言没有达到?以我的观点,正是因为需要运行高性能使得他的写法更偏向C,且没有自动内存管理等优点,写出的代码健壮性在初级或者中级开发人员手中不容易保证,所以在实际业务方面使用的会很少,再比如java,虽然性能比C++低,但是从初级或者中级开发人员手中写出的代码无论从风格统一还是健壮性上来看,都远远高于C++的版本。也正是因为C++的具有的这些特点,所以其语法和各个知识点都需要开发人员无比细致的知晓,比如单例模式的应用。在我们实际用到单例模式的时候,往往觉得单例很简单。无非是将构造函数私有化,然后提供一个全局的静态类方法来进行访问该类的资源。但是在我们实际工程中,对此还是需要有一定的原理了解。

在我公司实际项目中使用单例是一种非常普遍的事。但是不是每个人都能了解到其中的细节,有可能会对整个工程都带来灾难性的影响。

在下面列举两个不同单例的写法,看上去类似,但是实际上有着很不同的作用。

代码A:


class classForSingleton3
{
public:
    static classForSingleton3 *getClassForSingleton3()
    {

        static classForSingleton3 *m = 0;
        if (m == 0)
        {
            m = new classForSingleton3();
        }
        return m;
    }

private:
    classForSingleton3();
};

代码B:


class classForSingleton4
{
public:
    static classForSingleton4 *getClassForSingleton4()
    {
        static classForSingleton4 m;
        return &m;
    }

private:
    classForSingleton4();
};

以上两种都是单例的写法,在实现上是达成了一致的效果,这个类无法被外部初始化,只能通过get方法获取。

但是在实际运用上是有差异的,代码A的单例并不是线程安全的写法,代码B才是线程安全的写法。

原因有这么几点:

1 一个类实例的构造函数是符合原子特性,只有执行完了,才有进入的可能。这一点,我在很多C++编程相关的书上都没有找到介绍。例如有一个类实例叫做a,a在使用的时候,会是多线程环境中使用,初始化的的时候,必定是在某一个线程中做的,而不是两个线程都做一遍。

2 代码A是先生成一个匿名实例,然后将匿名实例赋值给了函数内静态变量m,构造函数实际没有与m发生关联,在实际运行过程中,该构造函数可能会被同时调用两次。这一点我已经在下方提供的代码中证明过。

3 代码B构造函数是与函数内静态变量m发生直接关系,依据类的构造函数原子性原理,该实例只会生成一份。且执行一次,是目前最安全的解决方式。

4 十分推荐单例获取函数写在cpp文件中。

代码结构:

class1.h

文件中带有4个单例类的实现方式。

#ifndef __CLASS_1_H__
#define __CLASS_1_H__
#include "stdio.h"
#include <unistd.h>
#define LOG(id, fmt, ...) printf("thread %d at[%s:%d] " fmt "\n", id, __FUNCTION__, __LINE__, ##__VA_ARGS__);

class classForSingleton1
{
public:
    static classForSingleton1 *getClassForSingleton1();

private:
    classForSingleton1();
};

class classForSingleton2
{
public:
    static classForSingleton2 *getClassForSingleton2();

private:
    classForSingleton2();
};

class classForSingleton3
{
public:
#if 0
    static classForSingleton3 *getClassForSingleton3()
    {

        if (mclassForSingleton3 == 0)
        {
            mclassForSingleton3 = new classForSingleton3();
        }
        return mclassForSingleton3;
    }
#else

    static classForSingleton3 *getClassForSingleton3()
    {
        static classForSingleton3 *m = 0;
        if (m == 0)
        {
            m = new classForSingleton3();
        }
        return m;
    }

#endif
private:
    static classForSingleton3 *mclassForSingleton3;
    classForSingleton3();
};
class classForSingleton4
{
public:
    static classForSingleton4 *getClassForSingleton4()
    {
        static classForSingleton4 m;
        return &m;
    }

private:
    classForSingleton4();
};

#endif

classForSingleton1 是我推荐的方式,使用初始化函数的静态局部变量保存类实例。该类在测试的时候,按照预期得到唯一的实例。

classForSingleton2 是使用一个类指针保存当前实例,在多线程环境中,最终表现为,不同的其他cpp调用的时候得到的实例不一致,而且生成了两个实例的时候,最终也是不同的线程/cpp使用的实例不一致

classForSingleton3 与2一致,但是获取单例的代码写在了h文件中,其单例类也被初始化了两次,但是在最终使用的时候,有一个造成了内存泄漏,多个cpp使用的是同一个实例。

classForSingleton4 代码与1一致,其表现也与1一致。

 

class1.cpp

文件中,写入了四个单例类的构造函数。为了模拟多线程竞争的问题,每个构造函数都sleep一秒,且在进入构造和退出构造的时候都打印相关字符串。

#include "class1.h"

#include "stdlib.h"
#include "stdio.h"

classForSingleton3 *classForSingleton3::mclassForSingleton3 = 0;

classForSingleton1 *classForSingleton1::getClassForSingleton1()
{
    static classForSingleton1 m;
    return &m;
}

classForSingleton2 *classForSingleton2::getClassForSingleton2()
{
    static classForSingleton2 *m = 0;
    if (m == 0)
    {
        m = new classForSingleton2();
    }
    return m;
}

classForSingleton1::classForSingleton1()
{
    printf("classForSingleton1 start at addr: 0x%X\n", this);
    usleep(1000 * 1000);
    printf("classForSingleton1 end\n");
}

classForSingleton2::classForSingleton2()
{
    printf("classForSingleton2 start at addr: 0x%X\n", this);
    usleep(1000 * 1000);
    printf("classForSingleton2 end\n");
}

classForSingleton3::classForSingleton3()
{
    printf("classForSingleton3 start at addr: 0x%X\n", this);
    mclassForSingleton3 = 0;
    usleep(1000 * 1000);
    printf("classForSingleton3 end\n");
}

classForSingleton4::classForSingleton4()
{
    printf("classForSingleton4 start at addr: 0x%X\n", this);
    usleep(1000 * 1000);
    printf("classForSingleton4 end\n");
}

function1.h

定义的单例引用函数getS1_1,getS2_1,getS3_1,getS4_1,其内部实现如下面


#ifndef __FUNCTION1_H__
#define __FUNCTION1_H__

void getS1_1(int id);
void getS1_2(int id);
void getS1_3(int id);
void getS1_4(int id);

#endif

function1.cpp

#include "function1.h"
#include "class1.h"

void getS1_1(int id)
{
    void *ptr = classForSingleton1::getClassForSingleton1();
    LOG(id, "get addr : 0x%X", (int *)ptr);
    usleep(100);
    ptr = classForSingleton1::getClassForSingleton1();
    LOG(id, "get addr : 0x%X", (int *)ptr);
}
void getS1_2(int id)
{
    void *ptr = classForSingleton2::getClassForSingleton2();
    LOG(id, "get addr : 0x%X", (int *)ptr);
    usleep(100);
    ptr = classForSingleton2::getClassForSingleton2();
    LOG(id, "get addr : 0x%X", (int *)ptr);
}
void getS1_3(int id)
{
    void *ptr = classForSingleton3::getClassForSingleton3();
    LOG(id, "get addr : 0x%X", (int *)ptr);
    usleep(100);
    ptr = classForSingleton3::getClassForSingleton3();
    LOG(id, "get addr : 0x%X", (int *)ptr);
}
void getS1_4(int id)
{
    void *ptr = classForSingleton4::getClassForSingleton4();
    LOG(id, "get addr : 0x%X", (int *)ptr);
    usleep(100);
    ptr = classForSingleton4::getClassForSingleton4();
    LOG(id, "get addr : 0x%X", (int *)ptr);
}

实现了四个get函数的访问对应单例类。而且每个都访问两次,查看其中的变动

function2.h与function2.cpp与function1.h和function1.cpp一致,就不放其内容,可以自己从代码上下下来,自己查阅。

 

test.cpp


#include "class1.h"
#include "function1.h"
#include "function2.h"
#include <thread>
#include <unistd.h>
using namespace std;
volatile int gIsOk = 0;
void firstThread()
{
    int id = 0;
    while (gIsOk != 1)
    {
    }
    LOG(id, "get s1 start");
    getS1_1(id);
    LOG(id, "get s1 end\n");
    gIsOk++;
    while (gIsOk != 3)
    {
    }
    LOG(id, "get s2 start");
    getS1_2(id);
    LOG(id, "get s2 end\n");
    gIsOk++;
    while (gIsOk != 5)
    {
    }
    LOG(id, "get s3 start");
    getS1_3(id);
    LOG(id, "get s3 end\n");
    gIsOk++;
    while (gIsOk != 7)
    {
    }
    LOG(id, "get s4 start");
    getS1_4(id);
    LOG(id, "get s4 end\n");
}
void secondThread()
{
    int id = 1;
    while (gIsOk != 1)
    {
    }
    LOG(id, "get s1 start");
    getS2_1(id);
    LOG(id, "get s1 end\n");
    gIsOk++;
    while (gIsOk != 3)
    {
    }
    LOG(id, "get s2 start");
    getS2_2(id);
    LOG(id, "get s2 end\n");
    gIsOk++;
    while (gIsOk != 5)
    {
    }
    LOG(id, "get s3 start");
    getS2_3(id);
    LOG(id, "get s3 end\n");
    gIsOk++;
    while (gIsOk != 7)
    {
    }
    LOG(id, "get s4 start");
    getS2_4(id);
    LOG(id, "get s4 end\n");
}

int main()
{
    thread t1(firstThread);
    t1.detach();
    thread t2(secondThread);
    t2.detach();
    gIsOk = 1;
    while (1)
    {
        usleep(100);
    }
    return 0;
}

在这个文件中,是测试程序的入口,从main函数中,我们创建了两个线程,模拟多线程竞争环境。也创建了一个变量。在每个线程中,分别调用不同的function的内容,最终的日志输出如下:

thread 0 at[firstThread:15] get s1 start
classForSingleton1 start at addr: 0x60B1B0
thread 1 at[secondThread:46] get s1 start
classForSingleton1 end
thread 0 at[getS1_1:7] get addr : 0x60B1B0
thread 1 at[getS2_1:8] get addr : 0x60B1B0
thread 0 at[getS1_1:10] get addr : 0x60B1B0
thread 0 at[firstThread:17] get s1 end
thread 1 at[getS2_1:11] get addr : 0x60B1B0
thread 1 at[secondThread:48] get s1 end

thread 1 at[secondThread:53] get s2 start
classForSingleton2 start at addr: 0xA00008C0
thread 0 at[firstThread:22] get s2 start
classForSingleton2 start at addr: 0x980008C0
classForSingleton2 end
thread 0 at[getS1_2:15] get addr : 0x980008C0
classForSingleton2 end
thread 1 at[getS2_2:16] get addr : 0xA00008C0
thread 1 at[getS2_2:19] get addr : 0xA00008C0
thread 1 at[secondThread:55] get s2 end
thread 0 at[getS1_2:18] get addr : 0x980008C0
thread 0 at[firstThread:24] get s2 end

thread 0 at[firstThread:29] get s3 start
thread 1 at[secondThread:60] get s3 start
classForSingleton3 start at addr: 0xA00008E0
classForSingleton3 start at addr: 0x980008E0
classForSingleton3 end
thread 0 at[getS1_3:23] get addr : 0x980008E0
classForSingleton3 end
thread 1 at[getS2_3:24] get addr : 0xA00008E0
thread 1 at[getS2_3:27] get addr : 0xA00008E0
thread 1 at[secondThread:62] get s3 end
thread 0 at[getS1_3:26] get addr : 0xA00008E0
thread 0 at[firstThread:31] get s3 end

thread 0 at[firstThread:36] get s4 start
classForSingleton4 start at addr: 0x60B1D0
thread 1 at[secondThread:67] get s4 start
classForSingleton4 end
thread 0 at[getS1_4:31] get addr : 0x60B1D0
thread 1 at[getS2_4:33] get addr : 0x60B1D0
thread 0 at[getS1_4:34] get addr : 0x60B1D0
thread 0 at[firstThread:38] get s4 end
thread 1 at[getS2_4:36] get addr : 0x60B1D0
thread 1 at[secondThread:69] get s4 end

可以从输出中看到的是,两个线程基本都是同时进入的每一对单例的获取函数。

在singleton1中,实例的构造函数被执行了1遍,两个线程都获取的是同一个实例。

在singleton2中,实例构造函数被执行了两次,且在多次获取实例的时候,最终形成的是每个function1/2拥有自己的实例。互不干扰,这是非常可怕的事情,比如在实际运行的时候,a线程负责加载某些资源然后全局共享。最终导致的问题就是莫名的崩溃了。

在singleton3中,构造函数也被执行了两次,但是可以注意到,在最终的第二次获取单例的时候,有一个实例被内存泄漏了,两个线程最终也是使用的同一个实例。也是非常危险的。

在singleton4中,构造函数被执行了一次,两个cpp中获取的实例也是一致的,但是这种写法,建议还是与singleton1保持一致,将单例获取函数的实现写在cpp当中是最为保险的。

这其中实际上有许多的c++编译的细节在其中体现。过于展开又会比较繁琐,就不一一说明了。

 

总结:

单例模式的使用,比我们想象中也有许多要注意的细节部分。建议参考singleton1的写法,最为安全。

代码地址:github代码地址

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值