atomic_wait

atomic_wait (값이 바뀔 때까지 대기)

atomic 객체의 값이 기대값과 같을 때 블록했다가 통지되면 깨어나는 원자 대기 연산이에요. C++20부터 있어요.

출처: cppreference

본문

atomic_wait는 원자 대기 연산을 수행해요.

template< class T >
void atomic_wait( const std::atomic<T>* object,
                  typename std::atomic<T>::value_type old );   // (1)

*object의 값을 old와 비교해서 같으면 블록하고, std::atomic_notify_one()/atomic_notify_all()(또는 std::atomic::notify_one/notify_all)로 통지될 때까지(또는 스퓨리어스하게 깨어날 때까지) 기다려요. 값이 old와 다르게 변할 때까지 이 과정을 반복해요.

_explicit 버전은 메모리 순서를 직접 지정할 수 있어요.

template< class T >
void atomic_wait_explicit( const std::atomic<T>* object,
                           typename std::atomic<T>::value_type old,
                           std::memory_order order );   // (3)
  • 매개변수 object: 대기할 atomic 객체 포인터.
  • 매개변수 old: 비교할 기대값.
  • 반환 값: 없음.

"특정 값이 될 때까지 CPU를 소모하며 폴링" 대신, 블록했다가 통지로 깨어나는 효율적인 대기를 만들 수 있어요.

std::atomic<int> flag{0};
// 다른 스레드가 flag = 1 저장 후 notify_all() 호출
std::atomic_wait(&flag, 0);   // flag가 0이 아닐 때까지 대기

wait/notify 짝으로 생산자-소비자 동기화를 스핀 없이 구현할 수 있어요.

더 알아보기 (Learn more)

cppreference