프로그래밍/Morden C++
std::call_once
MAKGA
2022. 3. 17. 21:21
320x100
https://en.cppreference.com/w/cpp/thread/call_once
std::call_once - cppreference.com
template< class Callable, class... Args > void call_once( std::once_flag& flag, Callable&& f, Args&&... args ); (since C++11) Executes the Callable object f exactly once, even if called concurrently, from several threads. In detail: If, by the time call_on
en.cppreference.com
여러 쓰레드에서 동시에 호출하더라도 딱 한번 호출됨을 보장해준다.
이를 위해 std::once_flag를 사용한다.
이럴 때 생각나는건 싱글톤 밖에 없는건 기분탓일까..
아래와 같이 작성하면 실제로 사용할 때 까지 메모리는 사용하지 않으면서, 안전한 인스턴스 객체를 생성할 수 있다(?)
#pragma once
#include <mutex>
#include <memory>
template<class _Class>
class JISingleTon
{
public:
static _Class& get_instance()
{
std::call_once(&flag_, [&ptr]() {
ptr_ = std::make_shared<_Class>(); });
return *instance;
}
JISingleTon() = default;
virtual ~JISingleTon() = default;
JISingleTon(const JISingleTon&) = delete;
JISingleTon& operator=(const JISingleTon&) = delete;
JISingleTon(JISingleTon&&) = delete;
JISingleTon& operator=(JISingleTon&&) = delete;
private:
static std::shared_ptr<_Class> ptr_;
static std::once_flag flag_;
};
template<class _Class>
std::shared_ptr<_Class> JISingleTon<_Class>::ptr_;
template<class _Class>
std::once_flag JISingleTon<_Class>::flag_;
하지만 게임 서버에선 굳이 실제 사용할 때까지 기다렸다가 생성을 할 필요가 없을 뿐더러(모든건 처음 시작할 때 메모리로 load), static 변수를 선언해 return 해주는게 더 간단한 방법 같다.
그냥 어떻게 사용하는지 기록용으로 남겨둔다.
320x100