std::thread 六:多线程&单例类

 

为了避免单例类在多线程中重复的创建,下面提供了两种解决方法:

  1.互斥锁+双重检查

  2.std::call_once()

 

方法一:互斥锁+双重检查

#include <iostream>
#include <thread>
#include <mutex>
#include <list>
using namespace std;

std::mutex my_mutex;

// 创建一个单例类
class MyCAS
{
private:
    MyCAS() {}                    // 私有化构造函数
    static MyCAS* m_instance;    // 静态成员变量

public:
    static MyCAS* GetInstance()
    {
        // 2.双重检查
        if (m_instance == NULL)
        {
            // 1.互斥锁
            std::lock_guard<std::mutex> mylock(my_mutex);
            if (m_instance == NULL)
            {
                m_instance = new MyCAS();
                static CGarhuishou ci;
            }
        }
        return m_instance;
    }

    // 类中封装一个类,用来析构单例类
    class CGarhuishou
    {
    public:
        ~CGarhuishou()
        {
            if (MyCAS::m_instance)
            {
                delete MyCAS::m_instance;
                MyCAS::m_instance = NULL;
            }
        }
    };

    void func() { cout << "test 123" << endl; }
};


// 类静态变量初始化
MyCAS* MyCAS::m_instance = NULL;


// 线程入口函数
void myThread()
{
    cout << "线程开始执行" << endl;
    MyCAS* p = MyCAS::GetInstance();
    cout << "线程结束执行" << endl;
}

int main()
{
    // 创建对象,但会对象指针
    std::thread t1(myThread);
    std::thread t2(myThread);

    t1.join();
    t2.join();

    return 0;
}

 

 

方法二:std::call_once()

#include <iostream>
#include <thread>
#include <mutex>
#include <list>
using namespace std;

std::once_flag g_flag;

// 创建一个单例类
class MyCAS
{
    // 只被调用一次
    static void CreateInstance()
    {
        m_instance = new MyCAS();
        static CGarhuishou ci;
    }

private:
    MyCAS() {}                   // 私有化构造函数
    static MyCAS* m_instance;    // 静态成员变量

public:
    static MyCAS* GetInstance()
    {
        std::call_once(g_flag, CreateInstance);
        return m_instance;
    }

    // 类中封装一个类,用来析构单例类
    class CGarhuishou
    {
    public:
        ~CGarhuishou()
        {
            if (MyCAS::m_instance)
            {
                delete MyCAS::m_instance;
                MyCAS::m_instance = NULL;
            }
        }
    };

    void func() { cout << "test 123" << endl; }
};


// 类静态变量初始化
MyCAS* MyCAS::m_instance = NULL;


// 线程入口函数
void myThread()
{
    cout << "线程开始执行" << endl;
    MyCAS* p = MyCAS::GetInstance();
    cout << "线程结束执行" << endl;
}

int main()
{
    // 创建对象,但会对象指针
    std::thread t1(myThread);
    std::thread t2(myThread);

    t1.join();
    t2.join();

    return 0;
}

 

posted @ 2023-06-18 23:20  十一的杂文录  阅读(16)  评论(0编辑  收藏  举报