Lab6: add barrier demo code
This commit is contained in:
parent
05f5ad82dc
commit
24d42d2c05
1 changed files with 37 additions and 0 deletions
37
lab6/demos/barriers.c
Normal file
37
lab6/demos/barriers.c
Normal 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;
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue