From 24d42d2c0565923913789a12f986a90bbc111289 Mon Sep 17 00:00:00 2001 From: Akemi Izuko Date: Sat, 19 Oct 2024 22:15:35 -0600 Subject: [PATCH] Lab6: add barrier demo code --- lab6/demos/barriers.c | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 lab6/demos/barriers.c diff --git a/lab6/demos/barriers.c b/lab6/demos/barriers.c new file mode 100644 index 0000000..ffc1f0a --- /dev/null +++ b/lab6/demos/barriers.c @@ -0,0 +1,37 @@ +#include +#include +#include + +#define NUM_THREADS 3 + +pthread_barrier_t barrier; + +void *thread_func(void *arg) { + int thread_id = *(int*) arg; + + printf("Thread %d is waiting at the barrier\n", thread_id); + pthread_barrier_wait(&barrier); + printf("Thread %d has passed the barrier\n", thread_id); + + return NULL; +} + +int main() { + pthread_t threads[NUM_THREADS]; + int thread_ids[NUM_THREADS]; + + pthread_barrier_init(&barrier, NULL, NUM_THREADS); + + for (int i = 0; i < NUM_THREADS; i++) { + thread_ids[i] = i; + pthread_create(threads + i, NULL, thread_func, &thread_ids[i]); + } + for (int i = 0; i < NUM_THREADS; i++) { + pthread_join(threads[i], NULL); + } + + pthread_barrier_destroy(&barrier); + + return 0; +} +