]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - packages/Python/lldbsuite/test/functionalities/stop-hook/multiple_threads/main.cpp
Vendor import of lldb trunk r256945:
[FreeBSD/FreeBSD.git] / packages / Python / lldbsuite / test / functionalities / stop-hook / multiple_threads / main.cpp
1 //===-- main.cpp ------------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include <chrono>
11 #include <cstdio>
12 #include <mutex>
13 #include <random>
14 #include <thread>
15
16 std::default_random_engine g_random_engine{std::random_device{}()};
17 std::uniform_int_distribution<> g_distribution{0, 3000000};
18
19 uint32_t g_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++ < 15)
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});
51
52         if (count < 7)
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
67     printf ("Before turning all three threads loose...\n"); // Set break point at this line, and add a stop-hook.
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     return 0;
77 }