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 // C includes
11 #include <pthread.h>
12 #include <stdio.h>
13 #include <stdint.h>
14 #include <stdlib.h>
15 #include <unistd.h>
16
17 pthread_t g_thread_1 = NULL;
18 pthread_t g_thread_2 = NULL;
19 pthread_t g_thread_3 = NULL;
20
21 uint32_t g_val = 0;
22
23 uint32_t access_pool (uint32_t flag = 0);
24
25 uint32_t
access_pool(uint32_t flag)26 access_pool (uint32_t flag)
27 {
28 static pthread_mutex_t g_access_mutex = PTHREAD_MUTEX_INITIALIZER;
29 if (flag == 0)
30 ::pthread_mutex_lock (&g_access_mutex);
31
32 uint32_t old_val = g_val;
33 if (flag != 0)
34 g_val = old_val + 1;
35
36 if (flag == 0)
37 ::pthread_mutex_unlock (&g_access_mutex);
38 return g_val;
39 }
40
41 void *
thread_func(void * arg)42 thread_func (void *arg)
43 {
44 uint32_t thread_index = *((uint32_t *)arg); // Break here to test that the stop-hook mechanism works for multiple threads.
45 printf ("%s (thread index = %u) startng...\n", __FUNCTION__, thread_index);
46
47 uint32_t count = 0;
48 uint32_t val;
49 while (count++ < 15)
50 {
51 // random micro second sleep from zero to 3 seconds
52 int usec = ::rand() % 3000000;
53 printf ("%s (thread = %u) doing a usleep (%d)...\n", __FUNCTION__, thread_index, usec);
54 ::usleep (usec);
55
56 if (count < 7)
57 val = access_pool ();
58 else
59 val = access_pool (1);
60
61 printf ("%s (thread = %u) after usleep access_pool returns %d (count=%d)...\n", __FUNCTION__, thread_index, val, count);
62 }
63 printf ("%s (thread index = %u) exiting...\n", __FUNCTION__, thread_index);
64 return NULL;
65 }
66
67
main(int argc,char const * argv[])68 int main (int argc, char const *argv[])
69 {
70 int err;
71 void *thread_result = NULL;
72 uint32_t thread_index_1 = 1;
73 uint32_t thread_index_2 = 2;
74 uint32_t thread_index_3 = 3;
75
76 printf ("Before turning all three threads loose...\n"); // Set break point at this line, and add a stop-hook.
77 // Create 3 threads
78 err = ::pthread_create (&g_thread_1, NULL, thread_func, &thread_index_1);
79 err = ::pthread_create (&g_thread_2, NULL, thread_func, &thread_index_2);
80 err = ::pthread_create (&g_thread_3, NULL, thread_func, &thread_index_3);
81
82 // Join all of our threads
83 err = ::pthread_join (g_thread_1, &thread_result);
84 err = ::pthread_join (g_thread_2, &thread_result);
85 err = ::pthread_join (g_thread_3, &thread_result);
86
87 return 0;
88 }
89