Namespaces
Variants

std::condition_variable:: notify_one

From cppreference.net

Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
void notify_one ( ) noexcept ;
(C++11 이후)

만약 어떤 스레드들이 * this 를 기다리고 있다면, notify_one 을 호출하면 대기 중인 스레드들 중 하나가 차단 해제됩니다.

참고 사항

notify_one() / notify_all() 의 효과와 wait() / wait_for() / wait_until() 의 세 가지 원자적 부분(잠금 해제+대기, 깨어남, 잠금)은 수정 순서 로 볼 수 있는 단일 전체 순서로 발생합니다: 이 순서는 해당 개별 조건 변수에 특정됩니다. 이로 인해 notify_one() 이 지연되어 notify_one() 호출 직후 대기를 시작한 스레드의 차단을 해제하는 것과 같은 상황이 발생하는 것이 불가능합니다.

알림을 보내는 스레드는 대기 중인 스레드가 보유한 뮤텍스와 동일한 뮤텍스의 잠금을 보유할 필요가 없습니다. 실제로 그렇게 하는 것은 비효율적입니다. 왜냐하면 알림을 받은 스레드는 알림을 보낸 스레드가 잠금을 해제하기를 기다리면서 즉시 다시 차단되기 때문입니다. 그러나 일부 구현(특히 pthreads의 많은 구현)은 이 상황을 인식하고, 대기 중인 스레드를 깨우지 않은 채 notify 호출 내에서 조건 변수의 큐에서 뮤텍스의 큐로 직접 전송함으로써 이러한 "급히 서두른 후 대기" 시나리오를 피합니다.

정확한 이벤트 스케줄링이 필요할 때는 락을 보유한 상태에서의 알림이 여전히 필요할 수 있습니다. 예를 들어, 대기 중인 스레드가 조건이 충족되면 프로그램을 종료하여 알림을 보내는 스레드의 조건 변수를 파괴하는 경우가 있습니다. 뮤텍스 언락 이후 알림 이전에 발생하는 가짜 깨어남(spurious wakeup)은 파괴된 객체에 대해 notify가 호출되는 결과를 초래할 수 있습니다.

예제

#include <chrono>
#include <condition_variable>
#include <iostream>
#include <thread>
using namespace std::chrono_literals;
std::condition_variable cv;
std::mutex cv_m;
int i = 0;
bool done = false;
void waits()
{
    std::unique_lock<std::mutex> lk(cv_m);
    std::cout << "Waiting... \n";
    cv.wait(lk, []{ return i == 1; });
    std::cout << "...finished waiting; i == " << i << '\n';
    done = true;
}
void signals()
{
    std::this_thread::sleep_for(200ms);
    std::cout << "Notifying falsely...\n";
    cv.notify_one(); // waiting thread is notified with i == 0.
                     // cv.wait wakes up, checks i, and goes back to waiting
    std::unique_lock<std::mutex> lk(cv_m);
    i = 1;
    while (!done) 
    {
        std::cout << "Notifying true change...\n";
        lk.unlock();
        cv.notify_one(); // waiting thread is notified with i == 1, cv.wait returns
        std::this_thread::sleep_for(300ms);
        lk.lock();
    }
}
int main()
{
    std::thread t1(waits), t2(signals);
    t1.join(); 
    t2.join();
}

가능한 출력:

Waiting... 
Notifying falsely...
Notifying true change...
...finished waiting; i == 1

참고 항목

대기 중인 모든 스레드에 알림
(public member function)
C documentation for cnd_signal