summaryrefslogtreecommitdiff
path: root/test/semaphore.cpp
blob: 09124ee8a6e9d51076363dda9afc2596d47177ba (plain)
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
#include "semaphore.h"

#ifndef __cpp_lib_semaphore
#	include <thread>

semaphore::semaphore(unsigned int v_) : v {v_} { }

void
semaphore::release(unsigned int n)
{
	std::lock_guard lk {m};
	v += n;
}

void
semaphore::acquire()
{
	while (!try_dec()) { }
}

bool
semaphore::try_dec()
{
	std::lock_guard lk {m};
	if (v) {
		v--;
		m.unlock();
		return true;
	}
	else {
		m.unlock();
		std::this_thread::sleep_for(std::chrono::milliseconds(100));
		return false;
	}
}

#endif