#include <iostream>#include <windows.h>#include <mutex>using namespace STD;STD:: Mutex _smutex;Template<TypeNameType>classsingleton{ Public:Statictype* Getsigleton () {if(Singlen = = NULL) {unique_lock<STD::mutex> Lock (_smutex);//c++11 the lock syntax. after the end of the//unique_lock life cycle, the lock objects it manages are unlocked, if(Singlen = = NULL) {#ifndef _win32#define _WIN32#endiftype* tmp =NewType (); Memorybarrier ();//Fence allows the previous code to execute before executing, preventing CPU optimizations causing confusion in multithreaded code execution. Singlen = tmp;//If direct Signlen = new Type ();//Here you have the space, call the construct, //Assignment Three-step operation may be confusing. } }returnSinglen; }Private:StaticType *singlen;//Prevent optimization so that each Singlen value is in memory. };Template<TypeNameType>type * Singleton<type>::singlen = NULL;classtest{ Public:voidPrintf () {cout<<"This is Test:: Printf ()"<< Endl; }};intMain () {singleton<test>:: Getsigleton ()->printf ();return 0;}
Singleton single-Case mode