Lab6: add barrier demo code

This commit is contained in:
Akemi Izuko 2024-10-19 22:15:35 -06:00
parent 05f5ad82dc
commit 24d42d2c05
Signed by: akemi
GPG key ID: 8DE0764E1809E9FC

37
lab6/demos/barriers.c Normal file
View file

@ -0,0 +1,37 @@
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#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;
}