thread_latch

thread_latch (스레드 래치)

latch 클래스는 std::ptrdiff_t 타입의 하향 카운터로, 스레드 동기화에 사용할 수 있어요. 카운터 값은 생성 시 초기화되고, 스레드는 카운터가 0이 될 때까지 latch에서 블록될 수 있답니다. 카운터를 증가시키거나 재설정할 수 없어서 latch는 일회용 배리어로 동작하며, std::latch의 멤버 함수(소멸자 제외)를 동시에 호출해도 데이터 경쟁이 발생하지 않아요.

출처: cppreference

본문

데이터 멤버 (Data Members)

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

멤버 함수 (Member functions)

이름 설명
(constructor) latch를 생성해요 (공개 멤버 함수)
(destructor) latch를 소멸해요 (공개 멤버 함수)
operator= [deleted] latch는 대입할 수 없어요 (공개 멤버 함수)
count_down 블록하지 않고 카운터를 감소시켜요 (공개 멤버 함수)
try_wait 내부 카운터가 0인지 검사해요 (공개 멤버 함수)
wait 카운터가 0이 될 때까지 블록돼요 (공개 멤버 함수)
arrive_and_wait 카운터를 감소시키고 0이 될 때까지 블록돼요 (공개 멤버 함수)

상수 (Constants)

이름 설명
max [static] 구현이 지원하는 카운터의 최대값 (공개 정적 멤버 함수)

Notes

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

예제 (Example)

#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

같이 보기 (See also)

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

더 알아보기 (Learn more)

cppreference