• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <chrono>
2 #include <cstdio>
3 #include <mutex>
4 #include <random>
5 #include <thread>
6 
7 std::default_random_engine g_random_engine{std::random_device{}()};
8 std::uniform_int_distribution<> g_distribution{0, 3000};
9 
10 uint32_t g_val = 0;
11 uint32_t lldb_val = 0;
12 
13 uint32_t
access_pool(bool flag=false)14 access_pool (bool flag = false)
15 {
16     static std::mutex g_access_mutex;
17     if (!flag)
18         g_access_mutex.lock();
19 
20     uint32_t old_val = g_val;
21     if (flag)
22         g_val = old_val + 1;
23 
24     if (!flag)
25         g_access_mutex.unlock();
26     return g_val;
27 }
28 
29 void
thread_func(uint32_t thread_index)30 thread_func (uint32_t thread_index)
31 {
32     // Break here to test that the stop-hook mechanism works for multiple threads.
33     printf ("%s (thread index = %u) startng...\n", __FUNCTION__, thread_index);
34 
35     uint32_t count = 0;
36     uint32_t val;
37     while (count++ < 4)
38     {
39         // random micro second sleep from zero to .3 seconds
40         int usec = g_distribution(g_random_engine);
41         printf ("%s (thread = %u) doing a usleep (%d)...\n", __FUNCTION__, thread_index, usec);
42         std::this_thread::sleep_for(std::chrono::microseconds{usec}); // Set break point at this line
43 
44         if (count < 2)
45             val = access_pool ();
46         else
47             val = access_pool (true);
48 
49         printf ("%s (thread = %u) after usleep access_pool returns %d (count=%d)...\n", __FUNCTION__, thread_index, val, count);
50     }
51     printf ("%s (thread index = %u) exiting...\n", __FUNCTION__, thread_index);
52 }
53 
54 
main(int argc,char const * argv[])55 int main (int argc, char const *argv[])
56 {
57     std::thread threads[3];
58     // Break here to set up the stop hook
59     printf("Stop hooks engaged.\n");
60     // Create 3 threads
61     for (auto &thread : threads)
62         thread = std::thread{thread_func, std::distance(threads, &thread)};
63 
64     // Join all of our threads
65     for (auto &thread : threads)
66         thread.join();
67 
68     // print lldb_val so we can check it here.
69     printf ("lldb_val was set to: %d.\n", lldb_val);
70     return 0;
71 }
72