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