xref: /haiku/src/tests/system/libroot/posix/pthread_barrier_test.cpp (revision 95c9effd68127df2dce202d5e254a7c86560010a)
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <pthread.h>
5 
6 #define THREAD_COUNT 10
7 #define CYCLES 2
8 
9 pthread_barrier_t mybarrier;
10 
11 void* threadFn(void* id_ptr)
12 {
13 	int thread_id = *(int*)id_ptr;
14 
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);
20 
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);
25 	}
26 
27 	return NULL;
28 }
29 
30 
31 int main()
32 {
33 	pthread_t ids[THREAD_COUNT];
34 	int short_ids[THREAD_COUNT];
35 
36 	srand(time(NULL));
37 	pthread_barrier_init(&mybarrier, NULL, THREAD_COUNT);
38 
39 	for (int i = 0; i < THREAD_COUNT; i++) {
40 		short_ids[i] = i;
41 		pthread_create(&ids[i], NULL, threadFn, &short_ids[i]);
42 	}
43 
44 	for (int i = 0; i < THREAD_COUNT; i++)
45 		pthread_join(ids[i], NULL);
46 
47 	pthread_barrier_destroy(&mybarrier);
48 
49 	return 0;
50 }
51 
52