10e0f49e7SDmytro Shynkevych #include <stdio.h>
20e0f49e7SDmytro Shynkevych #include <stdlib.h>
30e0f49e7SDmytro Shynkevych #include <unistd.h>
40e0f49e7SDmytro Shynkevych #include <pthread.h>
5*63396c7dSAugustin Cavalier #include <OS.h>
60e0f49e7SDmytro Shynkevych
70e0f49e7SDmytro Shynkevych #define THREAD_COUNT 10
8*63396c7dSAugustin Cavalier #define CYCLES 20
90e0f49e7SDmytro Shynkevych
100e0f49e7SDmytro Shynkevych pthread_barrier_t mybarrier;
110e0f49e7SDmytro Shynkevych
threadFn(void * id_ptr)120e0f49e7SDmytro Shynkevych void* threadFn(void* id_ptr)
130e0f49e7SDmytro Shynkevych {
140e0f49e7SDmytro Shynkevych int thread_id = *(int*)id_ptr;
150e0f49e7SDmytro Shynkevych
160e0f49e7SDmytro Shynkevych for (int i = 0; i < CYCLES; ++i) {
170e0f49e7SDmytro Shynkevych int wait_sec = 1 + rand() % 10;
18*63396c7dSAugustin Cavalier fprintf(stderr, "thread %d: Wait %d microseconds.\n", thread_id, wait_sec * 100);
19*63396c7dSAugustin Cavalier snooze(wait_sec * 100);
200e0f49e7SDmytro Shynkevych
21*63396c7dSAugustin Cavalier fprintf(stderr, "thread %d: Waiting on barrier...\n", thread_id);
220e0f49e7SDmytro Shynkevych int status = pthread_barrier_wait(&mybarrier);
230e0f49e7SDmytro Shynkevych if (status == PTHREAD_BARRIER_SERIAL_THREAD)
24*63396c7dSAugustin Cavalier fprintf(stderr, "thread %d: serial thread.\n", thread_id);
25*63396c7dSAugustin Cavalier fprintf(stderr, "thread %d: Finished!\n", thread_id);
260e0f49e7SDmytro Shynkevych }
270e0f49e7SDmytro Shynkevych
280e0f49e7SDmytro Shynkevych return NULL;
290e0f49e7SDmytro Shynkevych }
300e0f49e7SDmytro Shynkevych
310e0f49e7SDmytro Shynkevych
main()320e0f49e7SDmytro Shynkevych int main()
330e0f49e7SDmytro Shynkevych {
340e0f49e7SDmytro Shynkevych pthread_t ids[THREAD_COUNT];
350e0f49e7SDmytro Shynkevych int short_ids[THREAD_COUNT];
360e0f49e7SDmytro Shynkevych
370e0f49e7SDmytro Shynkevych srand(time(NULL));
380e0f49e7SDmytro Shynkevych pthread_barrier_init(&mybarrier, NULL, THREAD_COUNT);
390e0f49e7SDmytro Shynkevych
400e0f49e7SDmytro Shynkevych for (int i = 0; i < THREAD_COUNT; i++) {
410e0f49e7SDmytro Shynkevych short_ids[i] = i;
420e0f49e7SDmytro Shynkevych pthread_create(&ids[i], NULL, threadFn, &short_ids[i]);
430e0f49e7SDmytro Shynkevych }
440e0f49e7SDmytro Shynkevych
450e0f49e7SDmytro Shynkevych for (int i = 0; i < THREAD_COUNT; i++)
460e0f49e7SDmytro Shynkevych pthread_join(ids[i], NULL);
470e0f49e7SDmytro Shynkevych
480e0f49e7SDmytro Shynkevych pthread_barrier_destroy(&mybarrier);
490e0f49e7SDmytro Shynkevych
500e0f49e7SDmytro Shynkevych return 0;
510e0f49e7SDmytro Shynkevych }
520e0f49e7SDmytro Shynkevych
53