Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rdemeter
GitHub Repository: rdemeter/so
Path: blob/master/lab8/barrier.c
221 views
1
#define _XOPEN_SOURCE 600
2
#include <pthread.h>
3
#include <stdio.h>
4
5
pthread_barrier_t barrier;
6
#define NUM_THREADS 5
7
8
void *thread_routine(void *arg)
9
{
10
int thd_id = (int) arg;
11
int rc;
12
printf("thd %d: before teh barrier\n", thd_id);
13
14
// toate firele de executie asteapta la bariera.
15
rc = pthread_barrier_wait(&barrier);
16
if (rc == PTHREAD_BARRIER_SERIAL_THREAD) {
17
// un singur fir de execuie (posibil ultimul) va intoarce PTHREAD_BARRIER_SERIAL_THREAD
18
// restul firelor de execuie întorc 0 în caz de succes.
19
printf("thd %d let the flood in\n", thd_id);
20
}
21
printf("thd %d: after the barrier\n", thd_id);
22
return NULL;
23
}
24
25
int main()
26
{
27
int i;
28
pthread_t tids[NUM_THREADS];
29
30
// bariera este initializata o singura data si folosita de toate firele de executie
31
pthread_barrier_init(&barrier, NULL, NUM_THREADS);
32
33
// firele de executie vor executa codul functiei 'thread_routine'
34
// in locul unui pointer la date utile, se trimite in ultimul argument
35
// un intreg - identificatorul firului de executie
36
for (i = 0; i < NUM_THREADS; i++)
37
pthread_create(&tids[i], NULL, thread_routine, (void *) i);
38
39
// asteptam ca toate firele de executie sa se termine
40
for (i = 0; i < NUM_THREADS; i++)
41
pthread_join(tids[i], NULL);
42
43
// eliberam resursele barierei
44
pthread_barrier_destroy(&barrier);
45
return 0;
46
}
47
48
49