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