From 9d468d59a3ad22058bd07a7a171151695b829944 Mon Sep 17 00:00:00 2001 From: Yuanjun Ren Date: Tue, 26 Dec 2023 17:29:06 +0800 Subject: [PATCH] [CPP20]Add std::barrier examples --- CMakeLists.txt | 1 + cpp20_features/barrier_test.cc | 56 ++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 cpp20_features/barrier_test.cc diff --git a/CMakeLists.txt b/CMakeLists.txt index e35b48e..c824d59 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -56,6 +56,7 @@ add_executable(cpp_weekly cpp20_features/comparisons.cc cpp20_features/latches.cc + cpp20_features/barrier_test.cc cpp_challenges/chap1_math_problems.cc diff --git a/cpp20_features/barrier_test.cc b/cpp20_features/barrier_test.cc new file mode 100644 index 0000000..317162f --- /dev/null +++ b/cpp20_features/barrier_test.cc @@ -0,0 +1,56 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +void barrier_test() { + // initialize and print a collection of floating-point values: + std::vector values{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}; + + // define a lambda function that prints all values. + // -NOTE: has to be noexcept to be used as barrier callback + auto print_values = [&values]() noexcept { + for (auto val : values) { + std::cout << std::format("{:<7.5}", val); + } + std::cout << '\n'; + }; + + // print initial values: + print_values(); + + // initialize a barrier that prints the values when all threads have done + // their computations: + std::barrier all_done{ + int(values.size()), // initial value of the counter + print_values}; // callback to call whenever the counter is 0 + + // initialize a thread for each value to compute its square root in a loop: + std::vector threads; + threads.reserve(values.size()); + + for (auto &value : values) { + threads.emplace_back([&value, &values, &all_done] { + // repeatedly: + for (int i = 0; i < 5; ++i) { + // compute square root: + value = std::sqrt(value); + // and synchronize with other threads to print values: + all_done.arrive_and_wait(); + } + }); + } + + for (auto &t : threads) + t.join(); +} + +} // namespace + +TEST(barrier_test, basic_test) { barrier_test(); } \ No newline at end of file