summaryrefslogtreecommitdiff
path: root/libadhocutil/semaphore.cpp
blob: 0500445f2e55996c9c09b03a4f6074805b5c0278 (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
#include "semaphore.h"

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

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

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

	bool
	Semaphore::wait(unsigned int timeout)
	{
		const boost::system_time expiry = boost::get_system_time() + boost::posix_time::milliseconds(timeout);
		boost::mutex::scoped_lock lock(mutex);
		while (!count) {
			if (!condition.timed_wait(lock, expiry)) {
				return false;
			}
		}
		--count;
		return true;
	}
}