blob: d149fb35ce67b6552bbf0fa615e35440b407634c (
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
|
#include "Semaphore.h"
namespace TNet {
Semaphore::
Semaphore(int initValue)
{
mSemValue = initValue;
pthread_mutex_init(&mMutex, NULL);
pthread_cond_init(&mCond, NULL);
}
Semaphore::
~Semaphore()
{
pthread_mutex_destroy(&mMutex);
pthread_cond_destroy(&mCond);
}
int
Semaphore::
TryWait()
{
pthread_mutex_lock(&mMutex);
if(mSemValue > 0) {
mSemValue--;
pthread_mutex_unlock(&mMutex);
return 0;
}
pthread_mutex_unlock(&mMutex);
return -1;
}
void
Semaphore::
Wait()
{
pthread_mutex_lock(&mMutex);
while(mSemValue <= 0) {
pthread_cond_wait(&mCond, &mMutex);
}
mSemValue--;
pthread_mutex_unlock(&mMutex);
}
void
Semaphore::
Post()
{
pthread_mutex_lock(&mMutex);
mSemValue++;
pthread_cond_signal(&mCond);
pthread_mutex_unlock(&mMutex);
}
int
Semaphore::
GetValue()
{ return mSemValue; }
} //namespace
|