#include #include #include #include /* the number of threads */ int num_threads; /* our counter and condition */ int counter = 0; pthread_cond_t condition; pthread_mutex_t condition_mutex; /* the function called for each thread */ void* worker(void* idp) { /* get our thread id */ int id = * (int*) idp; /* we start to work */ printf("Thread %d starting!\n", id); /* simulate the threads taking slightly different amounts of time by sleeping * for our thread id seconds */ sleep(id); printf("Thread %d is done its work!\n", id); /***************** begin barrier here *****************/ /* lock the condition and increment the counter */ pthread_mutex_lock(&condition_mutex); counter++; /* if all the threads have incremented counter */ if (counter == num_threads) { /* reset the counter and broadcast the event to all waiting threads */ counter = 0; pthread_cond_broadcast(&condition); } else { /* otherwise not all threads are here yet, so we need to wait */ pthread_cond_wait(&condition, &condition_mutex); } /* unlock the condition mutex */ pthread_mutex_unlock(&condition_mutex); /***************** end barrier here *****************/ printf("Thread %d is past the barrier!\n", id); pthread_exit(NULL); } int main (int argc, char** argv) { /* get the number of threads */ if (argc < 2) { printf("Pass the number of threads to use!\n"); pthread_exit(0); } else { num_threads = atoi(argv[1]); } /* initialize the mutex and condition */ pthread_mutex_init(&condition_mutex, NULL); pthread_cond_init(&condition, NULL); /* an array of threads */ pthread_t threads[num_threads]; int ids[num_threads]; int i; /* spawn all threads */ for (i = 0; i < num_threads; i++) { ids[i] = i; pthread_create(&threads[i], NULL, worker, &ids[i]); } /* join all threads */ for (i = 0; i < num_threads; i++) { pthread_join(threads[i], NULL); } pthread_exit(0); }