-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBarrier.cpp
35 lines (29 loc) · 1019 Bytes
/
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
#include "Barrier.h"
Barrier::Barrier(unsigned int num_of_threads) : num_of_threads(num_of_threads),
threads_in_barrier(0) {
sem_init(&sem, 0, 0); // initialize semaphore
sem_init(&fence, 0, num_of_threads); // initialize semaphore
pthread_mutex_init(&mutex, NULL); // initialize mutex
}
void Barrier::wait() {
sem_wait(&fence);
pthread_mutex_lock(&mutex); // lock mutex
threads_in_barrier++;
if (threads_in_barrier == num_of_threads) { // release all
for (int i=0; i<num_of_threads; i++) sem_post(&sem);
}
pthread_mutex_unlock(&mutex); // unlock mutex
// barrier
sem_wait(&sem);
pthread_mutex_lock(&mutex); // lock mutex
threads_in_barrier--;
if (threads_in_barrier == 0) { // release fence
for (int i=0; i<num_of_threads; i++) sem_post(&fence);
}
pthread_mutex_unlock(&mutex); // unlock mutex
}
Barrier::~Barrier() {
sem_destroy(&sem);
sem_destroy(&fence);
pthread_mutex_destroy(&mutex);
}