std::call_once는 C++11에서 도입된 함수로, 여러 스레드가 동시에 실행되더라도 특정 작업이 딱 한 번만 실행되도록 보장하는 동기화 도구입니다.
주로 초기화가 한 번만 이루어져야 하는 경우에 사용됩니다 (예: 싱글톤 패턴 등).
#include <iostream>
#include <mutex>
#include <thread>
std::once_flag flag;
void initialize() {
std::call_once(flag, []() { std::cout << "Initialized once!" << std::endl; });
}
int main() {
std::thread t1(initialize);
std::thread t2(initialize);
t1.join();
t2.join();
return 0;
}
이 프로그램은 여러 스레드에서 initialize가 호출되더라도 std::call_once 내부의 람다가 단 한 번만 실행되도록 보장합니다.
🧠 사용 예시 요약
| 상황 | 설명 |
| 싱글톤 초기화 | 객체가 한 번만 생성되어야 할 때 |
| 리소스 초기화 | 설정 파일, 네트워크, DB 연결 등 |
| 한 번만 실행되어야 하는 코드 | 다중 스레드에서도 안정성 보장 |
reference
https://en.cppreference.com/w/cpp/thread/call_once.html
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 std::cal
en.cppreference.com
반응형
'프로그래밍 > C,C++' 카테고리의 다른 글
| [C++] 반환값 최적화(RVO, NRVO) (1) | 2025.05.14 |
|---|---|
| [Modern C++20] 🚀주요 특징 & 설명 (0) | 2025.04.16 |
| [Modern C++20] coroutine (0) | 2025.04.11 |
| [Modern C++20] concept (0) | 2025.04.08 |
| [Modern C++] string_view (0) | 2025.04.02 |