summaryrefslogtreecommitdiff
path: root/test/semaphore.cpp
blob: b7e089fc451bb267a4d19bfc16db0f70fa8df56d (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()
{
	m.lock();
	if (v) {
		v--;
		m.unlock();
		return true;
	}
	else {
		m.unlock();
		std::this_thread::sleep_for(std::chrono::milliseconds(100));
		return false;
	}
}

#endif