-
Notifications
You must be signed in to change notification settings - Fork 5
/
Semaphore.cpp
97 lines (89 loc) · 2.28 KB
/
Semaphore.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
#include "Semaphore.hpp"
#include "Exception.hpp"
#ifdef ___INANITY_PLATFORM_POSIX
#include <errno.h>
#endif
BEGIN_INANITY
Semaphore::Semaphore(int initialCount)
{
try
{
#if defined(___INANITY_PLATFORM_WINDOWS)
handle = CreateSemaphoreEx(NULL, initialCount, 0x7fffffff, NULL, 0, SEMAPHORE_ALL_ACCESS);
if(!handle.IsValid())
#elif defined(___INANITY_PLATFORM_MACOS)
sem = dispatch_semaphore_create(initialCount);
if(!sem)
#elif defined(___INANITY_PLATFORM_POSIX)
if(sem_init(&sem, 0, 0) != 0)
#else
#error Unknown platform
#endif
THROW_SECONDARY("Can't initialize semaphore", Exception::SystemError());
}
catch(Exception* exception)
{
THROW_SECONDARY("Can't create semaphore", exception);
}
}
Semaphore::~Semaphore()
{
#if defined(___INANITY_PLATFORM_WINDOWS)
CloseHandle(handle);
#elif defined(___INANITY_PLATFORM_MACOS)
dispatch_release(sem);
#elif defined(___INANITY_PLATFORM_POSIX)
sem_destroy(&sem);
#endif
}
void Semaphore::Acquire()
{
#if defined(___INANITY_PLATFORM_WINDOWS)
if(WaitForSingleObject(handle, INFINITE) != WAIT_OBJECT_0)
#elif defined(___INANITY_PLATFORM_MACOS)
if(dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER) != 0)
#elif defined(___INANITY_PLATFORM_POSIX)
if(sem_wait(&sem) != 0)
#else
#error Unknown platform
#endif
THROW_SECONDARY("Can't acquire semaphore", Exception::SystemError());
}
bool Semaphore::TryAcquire()
{
#if defined(___INANITY_PLATFORM_WINDOWS)
switch(WaitForSingleObject(handle, 0))
{
case WAIT_OBJECT_0:
return true;
case WAIT_TIMEOUT:
return false;
}
#elif defined(___INANITY_PLATFORM_MACOS)
return (dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER) == 0);
#elif defined(___INANITY_PLATFORM_POSIX)
if(sem_trywait(&sem) == 0)
return true;
if(errno == EAGAIN)
return false;
#else
#error Unknown platform
#endif
THROW_SECONDARY("Error trying acquire semaphore", Exception::SystemError());
}
void Semaphore::Release(int count)
{
#if defined(___INANITY_PLATFORM_WINDOWS)
if(!ReleaseSemaphore(handle, count, NULL))
#elif defined(___INANITY_PLATFORM_MACOS)
if(dispatch_semaphore_signal(sem), 0)
#elif defined(___INANITY_PLATFORM_POSIX)
int i;
for(i = 0; i < count && sem_post(&sem) == 0; ++i);
if(i < count)
#else
#error Unknown platform
#endif
THROW_SECONDARY("Can't release semaphore", Exception::SystemError());
}
END_INANITY