Skip to content

Commit

Permalink
[CPP20]Add std::latch examples
Browse files Browse the repository at this point in the history
  • Loading branch information
wtffqbpl committed Jan 3, 2024
1 parent 362bc7d commit 31f82c4
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions cpp20_features/latches.cc
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,71 @@ void latch_basic_test() {
t1.join();
t2.join();
}

// A boss-worker workflow using two std::latch

std::latch work_done{6};
std::latch go_home{1};

std::mutex cout_mutex;

void synchronized_out(const std::string &s) {
std::lock_guard<std::mutex> lo(cout_mutex);
std::cout << s;
}

class Worker {
public:
explicit Worker(std::string n) : name(std::move(n)) {}

void operator()() {
// Notify the boss when work is done
synchronized_out(name + ": " + "Work done!\n");
work_done.count_down();

// Waiting before going home
go_home.wait();
synchronized_out(name + ": " + "Good bye!\n");
}

private:
std::string name;
};

void boss_worker_workflow_test() {
std::cout << "BOSS: START WORKING! " << '\n';

std::vector<std::string> worker_name_list{
" Herb", " Scott", " Bjarne",
" Andrei", " Andrew", " David",
};

std::vector<Worker> worker_list;

worker_list.reserve(worker_name_list.size());
for (const auto &name : worker_name_list)
worker_list.emplace_back(name);

std::vector<std::thread> worker_thread_list;
worker_thread_list.reserve(worker_list.size());
for (auto &worker : worker_list)
worker_thread_list.emplace_back(worker);

work_done.wait();

go_home.count_down();

std::cout << "BOSS: GO HOME!\n";

for (auto &t : worker_thread_list)
t.join();
}
}

TEST(latch_test, basic_test) { latch_basic_test(); }

TEST(latch_test, test2) { boss_worker_workflow_test(); }

#endif // __APPLE__

#endif // __cplusplus >= 202002L

0 comments on commit 31f82c4

Please sign in to comment.