Namespaces
Variants

std::condition_variable:: notify_all

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_all ( ) noexcept ;
(C++11 이후)

현재 * this 를 기다리고 있는 모든 스레드의 차단을 해제합니다.

참고 사항

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

알림을 보내는 스레드는 대기 중인 스레드가 보유한 뮤텍스와 동일한 뮤텍스의 lock을 보유할 필요가 없습니다. 이를 수행하는 것은 비효율적일 수 있습니다. 왜냐하면 알림을 받은 스레드는 알림을 보내는 스레드가 lock을 해제하기를 기다리며 즉시 다시 block될 것이기 때문입니다. 하지만 일부 구현에서는 이 패턴을 인식하고 lock 아래에서 알림을 받은 스레드를 깨우려고 시도하지 않습니다.

예제

#include <chrono>
#include <condition_variable>
#include <iostream>
#include <thread>
std::condition_variable cv;
std::mutex cv_m; // 이 뮤텍스는 세 가지 목적으로 사용됩니다:
                 // 1) i에 대한 접근 동기화
                 // 2) std::cerr에 대한 접근 동기화
                 // 3) 조건 변수 cv를 위한 용도
int i = 0;
void waits()
{
    std::unique_lock<std::mutex> lk(cv_m);
    std::cerr << "Waiting... \n";
    cv.wait(lk, []{ return i == 1; });
    std::cerr << "...finished waiting. i == 1\n";
}
void signals()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
    {
        std::lock_guard<std::mutex> lk(cv_m);
        std::cerr << "Notifying...\n";
    }
    cv.notify_all();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    {
        std::lock_guard<std::mutex> lk(cv_m);
        i = 1;
        std::cerr << "Notifying again...\n";
    }
    cv.notify_all();
}
int main()
{
    std::thread t1(waits), t2(waits), t3(waits), t4(signals);
    t1.join(); 
    t2.join(); 
    t3.join();
    t4.join();
}

가능한 출력:

Waiting...
Waiting...
Waiting...
Notifying...
Notifying again...
...finished waiting. i == 1
...finished waiting. i == 1
...finished waiting. i == 1

참고 항목

대기 중인 하나의 스레드에 알림
(public member function)
C documentation for cnd_broadcast