aboutsummaryrefslogtreecommitdiff
path: root/lib/base/elock.cpp
blob: afddcc6f3b5a98ad8cf9289c06286615dc287c53 (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
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <lib/base/elock.h>
#include <unistd.h>

void eLock::lock(int res)
{
	if (res>max)
		res=max;
	pthread_mutex_lock(&mutex);
	while ((counter+res)>max)
		pthread_cond_wait(&cond, &mutex);
	counter+=res;
	pthread_mutex_unlock(&mutex);
}

void eLock::unlock(int res)
{
	if (res>max)
		res=max;
	pthread_mutex_lock(&mutex);
	counter-=res;
	pthread_mutex_unlock(&mutex);
	pthread_cond_signal(&cond);
}

eLock::eLock(int max): max(max)
{
	pthread_mutex_init(&mutex, 0);
	pthread_cond_init(&cond, 0);
	counter=0;
	pid=-1;
}

eLock::~eLock()
{
	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);
}

eLocker::eLocker(eLock &lock, int res): lock(lock), res(res)
{
	lock.lock(res);
}

eLocker::~eLocker()
{
	lock.unlock(res);
}

eSemaphore::eSemaphore()
{
	v=1;
	pthread_mutex_init(&mutex, 0);
	pthread_cond_init(&cond, 0);
}

eSemaphore::~eSemaphore()
{
	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);
}

int eSemaphore::down()
{
	int value_after_op;
	pthread_mutex_lock(&mutex);
	while (v<=0)
		pthread_cond_wait(&cond, &mutex);
	v--;
	value_after_op=v;
	pthread_mutex_unlock(&mutex);
	return value_after_op;
}

int eSemaphore::decrement()
{
	int value_after_op;
	pthread_mutex_lock(&mutex);
	v--;
	value_after_op=v;
	pthread_mutex_unlock(&mutex);
	pthread_cond_signal(&cond);
	return value_after_op;
}

int eSemaphore::up()
{
	int value_after_op;
	pthread_mutex_lock(&mutex);
	v++;
	value_after_op=v;
	pthread_mutex_unlock(&mutex);
	pthread_cond_signal(&cond);
	return value_after_op;
}

int eSemaphore::value()
{
	int value_after_op;
	pthread_mutex_lock(&mutex);
	value_after_op=v;
	pthread_mutex_unlock(&mutex);
	return value_after_op;
}