1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 #include <pthread.h> 5 #include <OS.h> 6 7 #define THREAD_COUNT 10 8 #define CYCLES 20 9 10 pthread_barrier_t mybarrier; 11 12 void* threadFn(void* id_ptr) 13 { 14 int thread_id = *(int*)id_ptr; 15 16 for (int i = 0; i < CYCLES; ++i) { 17 int wait_sec = 1 + rand() % 10; 18 fprintf(stderr, "thread %d: Wait %d microseconds.\n", thread_id, wait_sec * 100); 19 snooze(wait_sec * 100); 20 21 fprintf(stderr, "thread %d: Waiting on barrier...\n", thread_id); 22 int status = pthread_barrier_wait(&mybarrier); 23 if (status == PTHREAD_BARRIER_SERIAL_THREAD) 24 fprintf(stderr, "thread %d: serial thread.\n", thread_id); 25 fprintf(stderr, "thread %d: Finished!\n", thread_id); 26 } 27 28 return NULL; 29 } 30 31 32 int main() 33 { 34 pthread_t ids[THREAD_COUNT]; 35 int short_ids[THREAD_COUNT]; 36 37 srand(time(NULL)); 38 pthread_barrier_init(&mybarrier, NULL, THREAD_COUNT); 39 40 for (int i = 0; i < THREAD_COUNT; i++) { 41 short_ids[i] = i; 42 pthread_create(&ids[i], NULL, threadFn, &short_ids[i]); 43 } 44 45 for (int i = 0; i < THREAD_COUNT; i++) 46 pthread_join(ids[i], NULL); 47 48 pthread_barrier_destroy(&mybarrier); 49 50 return 0; 51 } 52 53