/* File: * busywait.c * * Purpose: * Illustrate busy waiting. * * Input: * none * Output: * message from each thread as the shared variable is incremented, followed * by the total at the end. * * Compile: gcc -g -Wall -o busywait busywait.c -lpthread * Usage: * ./busywait */ #include #include #include #include /* Global variable: accessible to all threads */ int num_threads; int shared_var = 1; int current_turn = 0; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; void *thread_function(void * thread_number); int main(int argc, char* argv[]) { if (argc != 2) { printf("usage: %s \n", argv[0]); return EXIT_SUCCESS; } num_threads = atoi(argv[1]); if (num_threads <= 0) { return EXIT_FAILURE; } pthread_t* thread_handles; thread_handles = malloc(num_threads * sizeof(pthread_t)); int thread; for (thread = 0; thread < num_threads; thread++) { pthread_create( &thread_handles[thread], NULL, thread_function, (void *) (long) thread); } for (thread = 0; thread < num_threads; thread++) { pthread_join(thread_handles[thread], NULL); } printf("Total: %d\n", shared_var); free(thread_handles); return 0; } void *thread_function(void* thread_number) { while (shared_var < 10000) { while (current_turn != (int) thread_number); if (shared_var < 10000) { shared_var = shared_var + 1; printf("Thread %ld increments to %d\n", (long) thread_number, shared_var); } current_turn++; if (current_turn >= num_threads) { current_turn = 0; } } return NULL; }