Boost::mutexを使ってシングルトンパターン

naohiro19
記事: 256
登録日時: 15年前
住所: 愛知県

Boost::mutexを使ってシングルトンパターン

投稿記事 by naohiro19 » 13年前

sp1章. 一つしかないことが保証できるsingletonでできるのはシングルスレッドのみですのでマルチスレッドようなものではできません。
マルチスレッド対応Singletonパターンを使うといいでしょう。

CODE:

#pragma once

#include 

class Singleton
{
private:
	static Singleton* m_pSingleton;
	static boost::mutex m_Mutex;

protected:
	/**
	 @brief コンストラクタ
	*/
	Singleton(){};
	/**
	 @brief デストラクタ
	*/
	~Singleton(){};
	/**
	 @brief 代入演算子オーバーロード
	*/
	Singleton &operator=(const Singleton&);
public:
	/**
	 @brief シングルトンアクセス関数
	*/
	static Singleton& get()
	{
		if( !m_pSingleton){
			boost::mutex::scoped_lock Lock(m_Mutex);
			if( !m_pSingleton){
				m_pSingleton = new Singleton;
			}
		}
		return *m_pSingleton;
	}
};
このクラスを継承させるためにコンストラクタ関連のはprotectedに変更しています。
最後に編集したユーザー naohiro19 on 2012年7月04日(水) 22:55 [ 編集 1 回目 ]

コメントはまだありません。