headers/bsd: Add sys/queue.h.
[haiku.git] / src / tests / system / libroot / posix / pthread_barrier_test.cpp
blobd9afc156a1b71242b466a21e3c48f0758584c9b5
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <pthread.h>
6 #define THREAD_COUNT 10
7 #define CYCLES 2
9 pthread_barrier_t mybarrier;
11 void* threadFn(void* id_ptr)
13 int thread_id = *(int*)id_ptr;
15 for (int i = 0; i < CYCLES; ++i) {
16 int wait_sec = 1 + rand() % 10;
17 printf("thread %d: Wait %d seconds.\n", thread_id, wait_sec);
18 sleep(wait_sec);
19 printf("thread %d: Waiting on barrier...\n", thread_id);
21 int status = pthread_barrier_wait(&mybarrier);
22 if (status == PTHREAD_BARRIER_SERIAL_THREAD)
23 printf("thread %d: serial thread.\n", thread_id);
24 printf("thread %d: Finished!\n", thread_id);
27 return NULL;
31 int main()
33 pthread_t ids[THREAD_COUNT];
34 int short_ids[THREAD_COUNT];
36 srand(time(NULL));
37 pthread_barrier_init(&mybarrier, NULL, THREAD_COUNT);
39 for (int i = 0; i < THREAD_COUNT; i++) {
40 short_ids[i] = i;
41 pthread_create(&ids[i], NULL, threadFn, &short_ids[i]);
44 for (int i = 0; i < THREAD_COUNT; i++)
45 pthread_join(ids[i], NULL);
47 pthread_barrier_destroy(&mybarrier);
49 return 0;