-
Notifications
You must be signed in to change notification settings - Fork 0
/
Barrier.cpp
48 lines (43 loc) · 1.01 KB
/
Barrier.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include "Barrier.h"
#include <cstdlib>
#include <cstdio>
Barrier::Barrier(int numThreads)
: mutex(PTHREAD_MUTEX_INITIALIZER)
, cv(PTHREAD_COND_INITIALIZER)
, count(0)
, numThreads(numThreads)
{ }
Barrier::~Barrier()
{
if (pthread_mutex_destroy(&mutex) != 0) {
fprintf(stderr, "[[Barrier]] error on pthread_mutex_destroy");
exit(1);
}
if (pthread_cond_destroy(&cv) != 0){
fprintf(stderr, "[[Barrier]] error on pthread_cond_destroy");
exit(1);
}
}
void Barrier::barrier()
{
if (pthread_mutex_lock(&mutex) != 0){
fprintf(stderr, "[[Barrier]] error on pthread_mutex_lock");
exit(1);
}
if (++count < numThreads) {
if (pthread_cond_wait(&cv, &mutex) != 0){
fprintf(stderr, "[[Barrier]] error on pthread_cond_wait");
exit(1);
}
} else {
count = 0;
if (pthread_cond_broadcast(&cv) != 0) {
fprintf(stderr, "[[Barrier]] error on pthread_cond_broadcast");
exit(1);
}
}
if (pthread_mutex_unlock(&mutex) != 0) {
fprintf(stderr, "[[Barrier]] error on pthread_mutex_unlock");
exit(1);
}
}