summary refs log tree commit diff stats
path: root/lib/genode_cpp/syslocks.h
blob: b5d5ae6943586dc13c8f4fc201f1435ae03ac76f (plain) (blame)
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
 *
 *           Nim's Runtime Library
 *       (c) Copyright 2017 Emery Hemingway
 *
 *   See the file "copying.txt", included in this
 *   distribution, for details about the copyright.
 *
 */

#ifndef _GENODE_CPP__SYSLOCKS_H_
#define _GENODE_CPP__SYSLOCKS_H_

/* Genode includes */
#include <base/semaphore.h>
#include <base/mutex.h>

namespace Nim {
	struct SysLock;
	struct SysCond;
}

struct Nim::SysLock
{
	Genode::Mutex _mutex_a, _mutex_b;
	bool         _locked;

	void acquireSys()
	{
		Genode::Mutex::Guard guard(_mutex_a);
		_locked = true;
		_mutex_b.acquire();
	}

	bool tryAcquireSys()
	{
		if (_locked)
			return false;

		Genode::Mutex::Guard guard(_mutex_a);

		if (_locked) {
			return false;
		} else {
			_locked = true;
			_mutex_b.acquire();
			return true;
		}
	}

	void releaseSys()
	{
		Genode::Mutex::Guard guard(_mutex_a);
		_locked = false;
		_mutex_b.release();
	}
};

struct Nim::SysCond
{
	Genode::Semaphore _semaphore;

	void waitSysCond(SysLock &syslock)
	{
		syslock.releaseSys();
		_semaphore.down();
		syslock.acquireSys();
	}

	void signalSysCond()
	{
		_semaphore.up();
	}

	void broadcastSysCond()
	{
		_semaphore.up();
	}
};

#endif