-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsemaphore.h
88 lines (75 loc) · 1.5 KB
/
semaphore.h
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
#ifndef _CU_SEMAPHORE_H_
#define _CU_SEMAPHORE_H_
#include <teelogging/teelogging.h>
#include "parallel_scheduler.h"
namespace cu {
static int last_id = 0;
class semaphore
{
public:
explicit semaphore(cu::parallel_scheduler& sche, int count_initial = 0)
: _sche(sche)
, _count(count_initial)
, _id(last_id++)
{
LOGV("<%d> created semaphore %d", _id, _count);
}
//! avisar / signal / unlock / up / wakeup / release / V
void notify()
{
++_count;
LOGV("<%d> increase semaphore from %d to %d", _id, _count-1, _count);
if(_count <= 0)
{
_sche.notify_one(_id);
}
}
void notify(cu::yield_type& yield)
{
++_count;
LOGV("<%d> increase semaphore from %d to %d", _id, _count-1, _count);
if(_count <= 0)
{
if(_sche.notify_one(_id))
{
LOGV("notify yield in semaphore %d", _id);
yield( cu::control_type{} );
}
}
}
//! esperar / wait / lock / down / sleep / P
void wait()
{
--_count;
LOGV("<%d> decrease semaphore from %d to %d", _id, _count+1, _count);
if(_count < 0)
{
LOGV("wait no-yield in semaphore %d", _id);
_sche.wait(_id);
}
}
void wait(cu::yield_type& yield)
{
--_count;
LOGV("<%d> decrease semaphore from %d to %d", _id, _count+1, _count);
if(_count < 0)
{
_sche.wait(_id);
LOGV("wait yield in semaphore %d", _id);
yield( cu::control_type{} );
}
}
inline bool empty() const
{
return (_count <= 0);
}
inline int size() const
{
return _count;
}
cu::parallel_scheduler& _sche;
int _count;
int _id;
};
}
#endif