-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathsema.cpp
102 lines (90 loc) · 2.29 KB
/
sema.cpp
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
/***********************************************************************
* Copyright (c) 2012, Baidu Inc. All rights reserved.
*
* Licensed under the BSD License
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* license.txt
*********************************************************************/
#include "sema.h"
#include "time_util.h"
#include "bgcc_error.h"
namespace bgcc {
Semaphore::Semaphore(int ninit) {
if (ninit < 0) {
ninit = 0;
}
#ifdef _WIN32
_sem = CreateSemaphore(NULL, ninit, LONG_MAX, NULL);
#else
sem_init(&_sem, 0, ninit);
#endif
}
Semaphore::~Semaphore() {
#ifdef _WIN32
if (NULL != _sem) {
BOOL ret = CloseHandle(_sem);
if (0 != ret) {
_sem = NULL;
}
}
#else
sem_destroy(&_sem);
#endif
}
int32_t Semaphore::wait(uint32_t millisecond) {
#ifdef _WIN32
if (NULL == _sem) {
return E_BGCC_NULL_POINTER;
}
DWORD ret = WaitForSingleObject(_sem, millisecond);
if (WAIT_OBJECT_0 == ret || WAIT_ABANDONED == ret) {
return 0;
}
else if (WAIT_TIMEOUT == ret) {
return E_BGCC_TIMEOUT;
}
else {
return E_BGCC_SYSERROR;
}
#else
int32_t ret = 0;
if (BGCC_SEMA_WAIT_INFINITE == millisecond) {
ret = sem_wait(&_sem);
}
else {
struct timespec ts = {0, 0};
TimeUtil::get_abs_timespec(&ts, millisecond);
ret = sem_timedwait(&_sem, &ts);
}
if (-1 == ret) {
int32_t e = BgccGetLastError();
if (ETIMEDOUT == e) {
return E_BGCC_TIMEOUT;
}
else {
return E_BGCC_SYSERROR;
}
}
return 0;
#endif
}
int32_t Semaphore::signal() {
#ifdef _WIN32
BOOL ret = FALSE;
if (NULL != _sem) {
ret = ReleaseSemaphore(_sem, 1, NULL);
}
return (0 != ret ? 0 : E_BGCC_SYSERROR);
#else
int32_t ret = sem_post(&_sem);
if (-1 == ret) {
return E_BGCC_SYSERROR;
}
else {
return 0;
}
#endif
}
}