#include #include #include #include pthread_mutex_t mutex_counter = PTHREAD_MUTEX_INITIALIZER; int counter = 0; void *thread_func(void *arg) { int unlocked = 0; while (counter < 1000000) { if ((int) arg == 0) { sleep(1); } pthread_mutex_lock(&mutex_counter); counter++; unlocked++; pthread_mutex_unlock(&mutex_counter); } printf("I am thread %d and got access %d times!\n", (int) arg, unlocked); return 0; } int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; int num_threads = 10; thread_handles = malloc(num_threads * sizeof(pthread_t)); for (thread = 0; thread < num_threads; thread++) { pthread_create(&thread_handles[thread], NULL, thread_func, (void*) thread); } for (thread = 0; thread < num_threads; thread++) { pthread_join(thread_handles[thread], NULL); } return 0; }