首页 > 其他 > 详细

单例模式

时间:2019-10-17 17:16:13      阅读:73      评论:0      收藏:0      [点我收藏+]

#include <mutex>
#include <thread>
#include <sstream>
#include <iostream>
#include <vector>


std::once_flag g_flag;

class Singleton
{
private:
    Singleton(){}
    static void CreateInstance()
    {
        pToSelf = new Singleton();
        static ToDestroy destroy;
    }

public:
    static Singleton* getInstance()
    {
        std::call_once(g_flag, CreateInstance);
        return pToSelf;
    } 

private:
    static Singleton* pToSelf;

    class ToDestroy
    {
    public:
        ~ToDestroy()
        {
            if(Singleton::pToSelf)
            {
                delete Singleton::pToSelf;
                pToSelf = nullptr;
                std::cout << "~ToDestroy() call \n";
            }
        }
    };
};

Singleton* Singleton::pToSelf = nullptr;



struct pcout: public std::stringstream
{
    ~pcout()
    {
        std::lock_guard<std::mutex> lk(pMutex);
        std::cout << rdbuf();
        std::cout.flush();
    }
private:
    static std::mutex pMutex;
};

std::mutex pcout::pMutex;

void func()
{
   
    Singleton *p = Singleton::getInstance();

    // cout 非线程安全   printf是线程安全
    // std::cout << "thread id : " << std::this_thread::get_id() << ' ' << (p) << std::endl;

    pcout{} << "thread id : " << std::this_thread::get_id() << ' ' << (p) << std::endl;
}

int main(void)
{
    std::vector<std::thread> threads;

    for(size_t i = 0; i<10; ++i)
    {
        threads.emplace_back(func);
    }
    
    for(auto &it : threads)
        it.join();

    return 0;
}

单例模式

原文:https://www.cnblogs.com/s3320/p/11692936.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!