summaryrefslogtreecommitdiff
path: root/libadhocutil/semaphore.cpp
blob: 38ff0fe9f04c5083993bf9bcacaba9d4b86d46de (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
38
39
40
41
42
43
44
45
46
#include "semaphore.h"

namespace AdHoc {
	Semaphore::Semaphore(unsigned int initial) : count(initial)
	{
	}

	void
	Semaphore::notify()
	{
		std::scoped_lock lock(mutex);
		++count;
		condition.notify_one();
	}

	void
	Semaphore::wait()
	{
		std::unique_lock lock(mutex);
		while (!count) {
			condition.wait(lock);
		}
		--count;
	}

	bool
	Semaphore::wait(unsigned int timeout)
	{
		const auto expiry = std::chrono::milliseconds(timeout);
		std::unique_lock lock(mutex);
		while (!count) {
			if (condition.wait_for(lock, expiry) == std::cv_status::timeout) {
				return false;
			}
		}
		--count;
		return true;
	}

	unsigned int
	Semaphore::freeCount() const
	{
		return count;
	}
}