Namespaces
Variants

std:: latch

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
latch
(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
헤더에 정의됨 <latch>
class latch ;
(C++20부터)

latch 클래스는 스레드 동기화에 사용될 수 있는 std::ptrdiff_t 타입의 감소 카운터입니다. 카운터 값은 생성 시 초기화됩니다. 스레드들은 카운터가 0으로 감소할 때까지 래치에서 대기할 수 있습니다. 카운터를 증가시키거나 재설정할 수 있는 방법이 없어, 래치를 일회성 배리어로 만듭니다.

std::latch 의 멤버 함수들(소멸자 제외)을 동시에 호출해도 데이터 경쟁(data race)이 발생하지 않습니다.

목차

데이터 멤버

이름 정의
std::ptrdiff_t counter 내부 카운터
( 설명 전용 멤버 객체* )

멤버 함수

latch 를 생성합니다
(public member function)
latch 를 파괴합니다
(public member function)
operator=
[deleted]
latch 는 할당할 수 없습니다
(public member function)
카운터를 비차단 방식으로 감소시킵니다
(public member function)
내부 카운터가 0인지 테스트합니다
(public member function)
카운터가 0이 될 때까지 블록합니다
(public member function)
카운터를 감소시키고 0이 될 때까지 블록합니다
(public member function)
상수
[static]
구현에서 지원하는 카운터의 최대값
(public static member function)

참고 사항

기능 테스트 매크로 표준 기능
__cpp_lib_latch 201907L (C++20) std::latch

예제

#include <functional>
#include <iostream>
#include <latch>
#include <string>
#include <thread>
struct Job
{
    const std::string name;
    std::string product{"not worked"};
    std::thread action{};
};
int main()
{
    Job jobs[]{{"Annika"}, {"Buru"}, {"Chuck"}};
    std::latch work_done{std::size(jobs)};
    std::latch start_clean_up{1};
    auto work = [&](Job& my_job)
    {
        my_job.product = my_job.name + " worked";
        work_done.count_down();
        start_clean_up.wait();
        my_job.product = my_job.name + " cleaned";
    };
    std::cout << "Work is starting... ";
    for (auto& job : jobs)
        job.action = std::thread{work, std::ref(job)};
    work_done.wait();
    std::cout << "done:\n";
    for (auto const& job : jobs)
        std::cout << "  " << job.product << '\n';
    std::cout << "Workers are cleaning up... ";
    start_clean_up.count_down();
    for (auto& job : jobs)
        job.action.join();
    std::cout << "done:\n";
    for (auto const& job : jobs)
        std::cout << "  " << job.product << '\n';
}

출력:

Work is starting... done:
  Annika worked
  Buru worked
  Chuck worked
Workers are cleaning up... done:
  Annika cleaned
  Buru cleaned
  Chuck cleaned

참고 항목

(C++20)
재사용 가능한 스레드 배리어
(클래스 템플릿)