C++11 call_once()을 사용하여 thread에 안전한 singleton 구현하기
C++11 call_once()을 사용하여 thread에 안전한 singleton 구현하기
Singleton 객체를 생성하는 방법은 다양하게 있다. template을 사용하는 방법, thread을 사용하는 방법 등.. 하지만 multi-thread 상태에서 singleton을 생성할 때는 상황에 따라서 인스턴스가 두 개 이상 생성될 수 있는 등 원하지 않는 동작을 할 경우가 있다.
1. Thread을 고려하지 않은 Singleton 생성
우선 다음 코드는 Thread을 고려하지 않고 Template을 사용한 Singleton 생성 방법이다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename T> | |
class ccSingleton { | |
public: | |
static T& instance() { | |
static T me; | |
return me; | |
} | |
}; |
위 코드는 Thread를 고려하지 않기 때문에 생성때 예상하지 못하는 오류들이 발생할 수 있다.
2. call_once()기반 thread에 안전한 Singleton 생성
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template<typename T> | |
class ccSingleton { | |
public: | |
static T& instance() { | |
std::call_once(singleton_flag_, []() { | |
instance_ = std::make_shared<T>(); | |
}); | |
return *instance_; | |
} | |
private: | |
static std::once_flag singleton_flag_; | |
static std::shared_ptr<T> instance_; | |
}; | |
template<typename T> | |
std::once_flag ccSingleton<T>::singleton_flag_; | |
template<typename T> | |
std::shared_ptr<T> ccSingleton<T>::instance_; |
댓글
댓글 쓰기