Namespaces
Variants

std:: notify_all_at_thread_exit

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
notify_all_at_thread_exit
(C++11)
(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
헤더 파일에 정의됨 <condition_variable>
void notify_all_at_thread_exit ( std:: condition_variable & cond,
std:: unique_lock < std:: mutex > lk ) ;
(C++11부터)

notify_all_at_thread_exit 는 주어진 스레드가 모든 thread_local 객체를 파괴하는 것을 포함하여 완전히 종료되었음을 다른 스레드에 알리기 위한 메커니즘을 제공합니다. 다음과 같이 동작합니다:

  • 이전에 획득한 락 lk 의 소유권이 내부 저장소로 이전됩니다.
  • 실행 환경이 수정되어 현재 스레드가 종료될 때, 조건 변수 cond 가 다음과 같이 통지받도록 설정됩니다: lk. unlock ( ) ;
    cond. notify_all ( ) ;
    .

암묵적인 lk. unlock ( ) 는 현재 스레드와 연관된 모든 thread local storage duration 을 가진 객체들의 소멸 이후에 순서가 지정됩니다 .

다음 조건 중 하나라도 충족되면, 동작은 정의되지 않습니다:

  • lk 가 호출 스레드에 의해 잠겨 있지 않습니다.
  • 다른 스레드들도 cond 를 대기 중인 경우, lk. mutex ( ) 는 해당 스레드들이 cond 에서 호출한 대기 함수들( wait , wait_for , wait_until )이 잠금 해제한 뮤텍스와 다릅니다.

목차

참고 사항

동일한 효과는 std::promise 또는 std::packaged_task 에서 제공하는 기능으로도 달성할 수 있습니다.

제공된 락 lk 은 스레드가 종료될 때까지 유지됩니다. 이 함수가 호출된 후에는 다른 스레드들이 cond 에서 대기하기 위해 동일한 락을 획득할 수 없습니다. 일부 스레드들이 이 조건 변수에서 대기 중인 경우, lk 의 락을 보유한 상태에서 대기 중인 조건이 충족되도록 보장해야 하며, 다른 스레드에서의 가짜 깨어남으로 인한 혼란을 피하기 위해 notify_all_at_thread_exit 을 호출하기 전에 이 락을 해제하고 재획득하지 않아야 합니다.

일반적인 사용 사례에서, 이 함수는 분리된 스레드에 의해 호출되는 마지막 작업입니다.

매개변수

cond - 스레드 종료 시 알림을 받을 조건 변수
lk - 조건 변수 cond 와 연관된 락

반환값

(없음)

예제

이 부분 코드 조각은 스레드 로컬 변수들이 소멸되는 과정 중에 스레드 로컬에 의존하는 데이터에 접근하는 것을 피하기 위해 notify_all_at_thread_exit 가 어떻게 사용될 수 있는지 보여줍니다:

#include <cassert>
#include <condition_variable>
#include <mutex>
#include <string>
#include <thread>
std::mutex m;
std::condition_variable cv;
bool ready = false;
std::string result; // some arbitrary type
void thread_func()
{
    thread_local std::string thread_local_data = "42";
    std::unique_lock<std::mutex> lk(m);
    // assign a value to result using thread_local data
    result = thread_local_data;
    ready = true;
    std::notify_all_at_thread_exit(cv, std::move(lk));
}   // 1. destroy thread_locals;
    // 2. unlock mutex;
    // 3. notify cv.
int main()
{
    std::thread t(thread_func);
    t.detach();
    // do other work
    // ...
    // wait for the detached thread
    std::unique_lock<std::mutex> lk(m);
    cv.wait(lk, []{ return ready; });
    // result is ready and thread_local destructors have finished, no UB
    assert(result == "42");
}

결함 보고서

다음 동작 변경 결함 보고서들은 이전에 발표된 C++ 표준에 소급 적용되었습니다.

DR 적용 대상 게시된 동작 올바른 동작
LWG 2140 C++11 notify_all_at_thread_exit 호출이
cond 에서 대기 중인 함수 호출과 동기화됨
동기화 요구사항을
업데이트함

참고 항목

결과를 특정 값으로 설정하면서 스레드 종료 시에만 알림을 전달함
( std::promise<R> 의 public 멤버 함수)
현재 스레드가 종료될 때만 결과가 준비되도록 함수를 실행함
( std::packaged_task<R(Args...)> 의 public 멤버 함수)