C++ Library Extensions 2022.12.09
To help learn modern C++ programming
009-synchronization.cpp
Go to the documentation of this file.
1#include <tpf_output.hpp>
2#include <future>
3#include <thread>
4#include <condition_variable>
5#include <atomic>
6
7constexpr int max_count = 12;
8constexpr int max_players = 3; // we will create 3 threads
9
10int whose_turn = 0;
11std::atomic<int> count{0};
12
13std::mutex mutex; // global mutex
14std::condition_variable condition_variable; // global condition variable
15
16
17// this is thread function
18void worker(const char* name, int my_turn)
19{
20 // if we do not use, std::atomic, it is incorrect
21 // by using std::atomic<int> count
22 while(count < max_count)
23 {
24 // unique_lock owns the global mutex
25 std::unique_lock<std::mutex> unique_lock(mutex);
26
27 condition_variable.wait(unique_lock,
28 [my_turn] { return (my_turn == whose_turn)
29 || (count >= max_count) ; });
30
31 if(count < max_count)
32 {
34
35 stream << count << ", " << name << " [ "
36 << std::this_thread::get_id() << " ]" << tpf::endl;
37
38 ++count; ++whose_turn;
39
41 whose_turn = 0;
42
43 // notify other threads to wakeup
44 condition_variable.notify_all();
45 }
46 else
47 {
48 // notify other threads to wakeup
49 condition_variable.notify_all();
50 break;
51 }
52 }
53}
54
56{
57 try
58 {
59 // std::async() returns a std::future<>;
60 auto f0 = std::async(std::launch::async, // start thread immediately
61 // if fails, it throws std::system_error
62 worker, // thread function
63 "A", 0 // worker's arguments
64 );
65
66 auto f1 = std::async(std::launch::async, worker, "B", 1);
67 auto f2 = std::async(std::launch::async, worker, "C", 2);
68
69 f0.get(); // wait until the thread ends (or returns)
70 f1.get();
71 f2.get();
72 }
73 catch(const std::system_error& e)
74 {
76 stream << e << tpf::endl;
77 }
78
79}
80
81int main()
82{
84}
std::mutex mutex
int whose_turn
constexpr int max_players
std::atomic< int > count
void worker(const char *name, int my_turn)
void example_for_synchronization()
std::condition_variable condition_variable
constexpr int max_count
int main()
tpf::sstream stream
constexpr auto endl
Definition: tpf_output.hpp:973
Stream output operators << are implemented.