1 //===-- main.cpp ------------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 #include <condition_variable>
16 std::default_random_engine g_random_engine{std::random_device{}()};
17 std::uniform_int_distribution<> g_distribution{0, 3000000};
18 std::condition_variable g_condition_variable;
22 char *g_char_ptr = nullptr;
27 std::unique_lock<std::mutex> lock{g_mutex};
29 g_condition_variable.wait(lock);
31 g_condition_variable.notify_all();
35 do_bad_thing_with_location(unsigned index, char *char_ptr, char new_val)
37 unsigned what = new_val;
38 printf("new value written to array(%p) and index(%u) = %u\n", char_ptr, index, what);
39 char_ptr[index] = new_val;
43 access_pool (bool flag = false)
45 static std::mutex g_access_mutex;
46 static unsigned idx = 0; // Well-behaving thread only writes into indexs from 0..6.
48 g_access_mutex.lock();
50 // idx valid range is [0, 6].
56 // Write into a forbidden area.
57 do_bad_thing_with_location(7, g_char_ptr, 99);
60 unsigned index = idx++;
63 g_access_mutex.unlock();
64 return g_char_ptr[index];
68 thread_func (uint32_t thread_index)
70 printf ("%s (thread index = %u) startng...\n", __FUNCTION__, thread_index);
78 // random micro second sleep from zero to 3 seconds
79 int usec = g_distribution(g_random_engine);
80 printf ("%s (thread = %u) doing a usleep (%d)...\n", __FUNCTION__, thread_index, usec);
81 std::this_thread::sleep_for(std::chrono::microseconds{usec});
86 val = access_pool (true);
88 printf ("%s (thread = %u) after usleep access_pool returns %d (count=%d)...\n", __FUNCTION__, thread_index, val, count);
90 printf ("%s (thread index = %u) exiting...\n", __FUNCTION__, thread_index);
94 int main (int argc, char const *argv[])
97 std::thread threads[3];
99 g_char_ptr = new char[10]{};
102 for (auto &thread : threads)
103 thread = std::thread{thread_func, std::distance(threads, &thread)};
109 } MyAggregateDataType;
111 printf ("Before turning all three threads loose...\n"); // Set break point at this line.
114 // Join all of our threads
115 for (auto &thread : threads)