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 char *g_char_ptr = NULL; 22 23 void 24 do_bad_thing_with_location(char *char_ptr, char new_val) 25 { 26 unsigned what = new_val; 27 printf("new value written to location(%p) = %u\n", char_ptr, what); 28 *char_ptr = new_val; 29 } 30 31 uint32_t access_pool (uint32_t flag = 0); 32 33 uint32_t 34 access_pool (uint32_t flag) 35 { 36 static pthread_mutex_t g_access_mutex = PTHREAD_MUTEX_INITIALIZER; 37 if (flag == 0) 38 ::pthread_mutex_lock (&g_access_mutex); 39 40 char old_val = *g_char_ptr; 41 if (flag != 0) 42 do_bad_thing_with_location(g_char_ptr, old_val + 1); 43 44 if (flag == 0) 45 ::pthread_mutex_unlock (&g_access_mutex); 46 return *g_char_ptr; 47 } 48 49 void * 50 thread_func (void *arg) 51 { 52 uint32_t thread_index = *((uint32_t *)arg); 53 printf ("%s (thread index = %u) startng...\n", __FUNCTION__, thread_index); 54 55 uint32_t count = 0; 56 uint32_t val; 57 while (count++ < 15) 58 { 59 // random micro second sleep from zero to 3 seconds 60 int usec = ::rand() % 3000000; 61 printf ("%s (thread = %u) doing a usleep (%d)...\n", __FUNCTION__, thread_index, usec); 62 ::usleep (usec); 63 64 if (count < 7) 65 val = access_pool (); 66 else 67 val = access_pool (1); 68 69 printf ("%s (thread = %u) after usleep access_pool returns %d (count=%d)...\n", __FUNCTION__, thread_index, val, count); 70 } 71 printf ("%s (thread index = %u) exiting...\n", __FUNCTION__, thread_index); 72 return NULL; 73 } 74 75 76 int main (int argc, char const *argv[]) 77 { 78 int err; 79 void *thread_result = NULL; 80 uint32_t thread_index_1 = 1; 81 uint32_t thread_index_2 = 2; 82 uint32_t thread_index_3 = 3; 83 84 g_char_ptr = (char *)malloc (1); 85 *g_char_ptr = 0; 86 87 // Create 3 threads 88 err = ::pthread_create (&g_thread_1, NULL, thread_func, &thread_index_1); 89 err = ::pthread_create (&g_thread_2, NULL, thread_func, &thread_index_2); 90 err = ::pthread_create (&g_thread_3, NULL, thread_func, &thread_index_3); 91 92 printf ("Before turning all three threads loose...\n"); // Set break point at this line. 93 94 // Join all of our threads 95 err = ::pthread_join (g_thread_1, &thread_result); 96 err = ::pthread_join (g_thread_2, &thread_result); 97 err = ::pthread_join (g_thread_3, &thread_result); 98 99 return 0; 100 } 101