-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLocklessSemaphore.cpp
More file actions
47 lines (38 loc) · 960 Bytes
/
LocklessSemaphore.cpp
File metadata and controls
47 lines (38 loc) · 960 Bytes
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
#include "LocklessSemaphore.hpp"
#include <iostream>
LocklessSemaphore::LocklessSemaphore(int initial_capacity)
: capacity(initial_capacity), sem(0) {}
LocklessSemaphore::~LocklessSemaphore() {
}
void LocklessSemaphore::shutdown() {
sem.shutdown();
}
long LocklessSemaphore::current() {
return capacity.load();
}
void LocklessSemaphore::post() {
long cap = capacity++;
if(cap < 0) {
// std::cout << "Posting." << std::endl;
sem.post();
}
}
long LocklessSemaphore::wait() {
long cap = capacity--;
if(cap <= 0) {
// std::cout << "Waiting." << std::endl;
sem.wait();
}
return cap - 1;
}
bool LocklessSemaphore::try_wait() {
long cap;
do {
cap = capacity.load();
if(cap <= 0) {
return false;
}
}while(!atomic_compare_exchange_weak(&capacity, &cap, cap - 1));
//std::cout << "Doing try_wait." << std::endl;
return true;
}