【设计模式:singleton pattern】

#include <iostream>
#include <thread>
#include <atomic>
#include <mutex>
#include <future>
#include <vector>

#define ATOMIC

#ifdef CALLONCE
std::once_flag f;
#endif
class Singleton;
inline Singleton *GetNullptr( void ){
	return ( Singleton *)nullptr;
}

class Singleton{
class dtor{
public:
	~dtor( void ){
		puts( "Dtor Called ");
		if( Singleton::m_instance )
			delete Singleton::m_instance;
		Singleton::m_instance = nullptr;
	}
};
private:
	Singleton( void ) { puts("Singleto default constructor called"); };
public:
	~Singleton( void ){ puts( "Singleto default destructor called" ); }
	explicit Singleton( const Singleton& ) = delete;
	Singleton( Singleton&& ) = delete;
	Singleton& operator=( const Singleton& ) = delete;
	Singleton& operator=( Singleton&& ) = delete;

	static Singleton& getInstance( void ){
#ifdef ATOMIC
		Singleton *t = m_instance.load( std::memory_order_relaxed );
		std::atomic_thread_fence( std::memory_order_acquire );
		if( !t ){
			std::lock_guard< std::mutex > locker( m_mutex );
			std::cout << "A thread hold the mutex and lock it" << std::endl;
			t = m_instance.load( std::memory_order_relaxed );
			if( !t ){
				t = new Singleton;
				static dtor d;
				std::atomic_thread_fence( std::memory_order_relaxed );
			}
		}
		if( t ) m_instance = t;
		return *m_instance;
 #elif defined CALLONCE
		std::call_once( f, [&]{ Singleton::CreateInstance(); } );
		return *m_instance;
 #endif
	}
	
protected:
	static std::atomic< Singleton * > m_instance;
#ifdef CALLONCE
	static inline void CreateInstance( void ){
		std::unique_lock< std::mutex > m_mutex;
		m_instance = new Singleton;
		static dtor d;
	}
 #endif
private:
	static std::mutex m_mutex;
};
std::mutex Singleton::m_mutex;
std::atomic< Singleton * > Singleton::m_instance( GetNullptr() );

int main( void ){
	int counter { 1000 };
	std::vector< std::future< void > > futrVec;
	while( counter-- ) futrVec.push_back( std::move( std::async( []{
		Singleton::getInstance(); })
		));
	for( auto& futr : futrVec ) futr.wait();
	
	puts( "All instance generating test done");
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XNB's Not a Beginner

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值