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