| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
#pragma once |
| 5 |
|
| 6 |
#ifdef _WIN32 |
| 7 |
|
| 8 |
#include <Windows.h> |
| 9 |
|
| 10 |
namespace Common |
| 11 |
{ |
| 12 |
class Semaphore |
| 13 |
{ |
| 14 |
public: |
| 15 |
Semaphore(int initial_count, int maximum_count) |
| 16 |
{ |
| 17 |
m_handle = CreateSemaphoreA(nullptr, initial_count, maximum_count, nullptr); |
| 18 |
} |
| 19 |
|
| 20 |
~Semaphore() { CloseHandle(m_handle); } |
| 21 |
void Wait() { WaitForSingleObject(m_handle, INFINITE); } |
| 22 |
void Post() { ReleaseSemaphore(m_handle, 1, nullptr); } |
| 23 |
|
| 24 |
private: |
| 25 |
HANDLE m_handle; |
| 26 |
}; |
| 27 |
} |
| 28 |
|
| 29 |
#elif defined(__APPLE__) |
| 30 |
|
| 31 |
#include <dispatch/dispatch.h> |
| 32 |
|
| 33 |
namespace Common |
| 34 |
{ |
| 35 |
class Semaphore |
| 36 |
{ |
| 37 |
public: |
| 38 |
Semaphore(int initial_count, int maximum_count) |
| 39 |
{ |
| 40 |
m_handle = dispatch_semaphore_create(0); |
| 41 |
for (int i = 0; i < initial_count; i++) |
| 42 |
dispatch_semaphore_signal(m_handle); |
| 43 |
} |
| 44 |
~Semaphore() { dispatch_release(m_handle); } |
| 45 |
void Wait() { dispatch_semaphore_wait(m_handle, DISPATCH_TIME_FOREVER); } |
| 46 |
void Post() { dispatch_semaphore_signal(m_handle); } |
| 47 |
|
| 48 |
private: |
| 49 |
dispatch_semaphore_t m_handle; |
| 50 |
}; |
| 51 |
} |
| 52 |
|
| 53 |
#else |
| 54 |
|
| 55 |
#include <semaphore.h> |
| 56 |
|
| 57 |
namespace Common |
| 58 |
{ |
| 59 |
class Semaphore |
| 60 |
{ |
| 61 |
public: |
| 62 |
Semaphore(int initial_count, int maximum_count) { sem_init(&m_handle, 0, initial_count); } |
| 63 |
~Semaphore() { sem_destroy(&m_handle); } |
| 64 |
void Wait() { sem_wait(&m_handle); } |
| 65 |
void Post() { sem_post(&m_handle); } |
| 66 |
|
| 67 |
private: |
| 68 |
sem_t m_handle; |
| 69 |
}; |
| 70 |
} |
| 71 |
|
| 72 |
#endif |