2 #include <condition_variable>
7 std::default_random_engine g_random_engine
{std::random_device
{}()};
8 std::uniform_int_distribution
<> g_distribution
{0, 3000000};
9 std::condition_variable g_condition_variable
;
13 char *g_char_ptr
= nullptr;
18 std::unique_lock
<std::mutex
> lock
{g_mutex
};
20 g_condition_variable
.wait(lock
);
22 g_condition_variable
.notify_all();
26 do_bad_thing_with_location(char *char_ptr
, char new_val
)
32 access_pool (bool flag
= false)
34 static std::mutex g_access_mutex
;
36 g_access_mutex
.lock();
38 char old_val
= *g_char_ptr
;
40 do_bad_thing_with_location(g_char_ptr
, old_val
+ 1);
43 g_access_mutex
.unlock();
48 thread_func (uint32_t thread_index
)
50 printf ("%s (thread index = %u) startng...\n", __FUNCTION__
, thread_index
);
58 // random micro second sleep from zero to 3 seconds
59 int usec
= g_distribution(g_random_engine
);
60 printf ("%s (thread = %u) doing a usleep (%d)...\n", __FUNCTION__
, thread_index
, usec
);
61 std::this_thread::sleep_for(std::chrono::microseconds
{usec
});
66 val
= access_pool (true);
68 printf ("%s (thread = %u) after usleep access_pool returns %d (count=%d)...\n", __FUNCTION__
, thread_index
, val
, count
);
70 printf ("%s (thread index = %u) exiting...\n", __FUNCTION__
, thread_index
);
74 int main (int argc
, char const *argv
[])
77 std::thread threads
[3];
79 g_char_ptr
= new char{};
82 for (auto &thread
: threads
)
83 thread
= std::thread
{thread_func
, std::distance(threads
, &thread
)};
85 printf ("Before turning all three threads loose...\n"); // Set break point at this line.
88 // Join all of our threads
89 for (auto &thread
: threads
)