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 型の下降カウンタです。カウンタの値は作成時に初期化されます。スレッドはカウンタがゼロにデクリメントされるまでラッチでブロックできます。カウンタを増加またはリセットする機能はないため、ラッチは単回使用のバリアとなります。

std::latch のメンバ関数の同時呼び出しは、デストラクタを除いて、データ競合を引き起こしません。

目次

データメンバ

名前 定義
std::ptrdiff_t counter 内部カウンター
( 説明専用メンバーオブジェクト* )

メンバー関数

latch を構築する
(public member function)
latch を破棄する
(public member function)
operator=
[deleted]
latch は代入不可
(public member function)
非ブロッキング方式でカウンタをデクリメントする
(public member function)
内部カウンタがゼロかどうかをテストする
(public member function)
カウンタがゼロに達するまでブロックする
(public member function)
カウンタをデクリメントし、ゼロに達するまでブロックする
(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)
再利用可能なスレッドバリア
(クラステンプレート)