#include #include #include #include #include #define NUMLOOPS 100000 int x = 0; sem_t sem; void *loop(void *); pthread_t create_thread(int); int main(int argc, char *argv[]) { pthread_t t1, t2; void *arg; int collisions = 0; int percentage = 0; int status = 0; // Initialize the semaphore status = sem_init(&sem, 0, 1); if(status < 0) { perror("seminit failed: "); exit(-1); } // Create thread 1 t1 = create_thread(1); // Create thread 2 t2 = create_thread(2); // Wait for both threads to finish pthread_join(t1, NULL); pthread_join(t2, NULL); // Calculate the results collisions = (NUMLOOPS*2 - x)/2; percentage = 100*((double)collisions/NUMLOOPS); // Print out the results if(collisions != 0) { printf("Race Condition! x = %d, should be %d\n", x, NUMLOOPS*2); printf("There were %d collisions! That's %d%% of all loops\n", collisions, percentage); } else { printf("No Race Condition. x = %d\n", x); } } /* * Create a thread */ pthread_t create_thread(int arg) { int status; pthread_t thread; // Create the thread status = pthread_create(&thread, NULL, loop, (void *)arg); // Make sure it worked if(status < 0) { printf("status = %d, errno = %d\n", status, errno); perror("pthread_create 1 failed: "); exit(-1); } // Return the thread pointer return thread; } /* * This is the code run by the two threads */ void *loop(void *foo) { int i; // This sleep allows the other thread to start // running before this one gets into the loop sleep(1); printf("Thread %d running\n", (int)foo); // Increment x many times for(i = 0; i < NUMLOOPS; i++) { //sem_wait(&sem); x = x+1; //sem_post(&sem); } printf("Thread %d done\n", (int)foo); return(NULL); }