2 #include <condition_variable>
6 std::condition_variable g_condition_variable
;
10 char *g_char_ptr
= nullptr;
15 std::unique_lock
<std::mutex
> lock
{g_mutex
};
17 g_condition_variable
.wait(lock
);
19 g_condition_variable
.notify_all();
23 do_bad_thing_with_location(unsigned index
, char *char_ptr
, char new_val
)
25 unsigned what
= new_val
;
26 printf("new value written to array(%p) and index(%u) = %u\n", char_ptr
, index
, what
);
27 char_ptr
[index
] = new_val
;
31 access_pool (bool flag
= false)
33 static std::mutex g_access_mutex
;
34 static unsigned idx
= 0; // Well-behaving thread only writes into indexs from 0..6.
36 g_access_mutex
.lock();
38 // idx valid range is [0, 6].
44 // Write into a forbidden area.
45 do_bad_thing_with_location(7, g_char_ptr
, 99);
48 unsigned index
= idx
++;
51 g_access_mutex
.unlock();
52 return g_char_ptr
[index
];
56 thread_func (uint32_t thread_index
)
58 printf ("%s (thread index = %u) startng...\n", __FUNCTION__
, thread_index
);
66 printf ("%s (thread = %u) sleeping for 1 second...\n", __FUNCTION__
, thread_index
);
67 std::this_thread::sleep_for(std::chrono::seconds(1));
72 val
= access_pool (true);
74 printf ("%s (thread = %u) after sleep access_pool returns %d (count=%d)...\n", __FUNCTION__
, thread_index
, val
, count
);
76 printf ("%s (thread index = %u) exiting...\n", __FUNCTION__
, thread_index
);
80 int main (int argc
, char const *argv
[])
83 std::thread threads
[3];
85 g_char_ptr
= new char[10]{};
88 for (auto &thread
: threads
)
89 thread
= std::thread
{thread_func
, std::distance(threads
, &thread
)};
95 } MyAggregateDataType
;
97 printf ("Before turning all three threads loose...\n"); // Set break point at this line.
100 // Join all of our threads
101 for (auto &thread
: threads
)