3 Copyright (C) 2013 sapier <sapier AT gmx DOT net>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "threading/semaphore.h"
26 #define UNUSED(expr) do { (void)(expr); } while (0)
29 #define MAX_SEMAPHORE_COUNT LONG_MAX - 1
34 #if defined(__MACH__) && defined(__APPLE__)
35 #include <mach/mach.h>
36 #include <mach/task.h>
37 #include <mach/semaphore.h>
38 #include <sys/semaphore.h>
46 #define sem_t semaphore_t
47 #define sem_init(s, p, c) semaphore_create(mach_task_self(), (s), 0, (c))
48 #define sem_wait(s) semaphore_wait(*(s))
49 #define sem_post(s) semaphore_signal(*(s))
50 #define sem_destroy(s) semaphore_destroy(mach_task_self(), *(s))
55 Semaphore::Semaphore(int val)
58 semaphore = CreateSemaphore(NULL, val, MAX_SEMAPHORE_COUNT, NULL);
60 int ret = sem_init(&semaphore, 0, val);
67 Semaphore::~Semaphore()
70 CloseHandle(semaphore);
72 int ret = sem_destroy(&semaphore);
74 // Workaround for broken bionic semaphore implementation!
75 assert(!ret || errno == EBUSY);
84 void Semaphore::post(unsigned int num)
88 ReleaseSemaphore(semaphore, num, NULL);
90 for (unsigned i = 0; i < num; i++) {
91 int ret = sem_post(&semaphore);
99 void Semaphore::wait()
102 WaitForSingleObject(semaphore, INFINITE);
104 int ret = sem_wait(&semaphore);
111 bool Semaphore::wait(unsigned int time_ms)
114 unsigned int ret = WaitForSingleObject(semaphore, time_ms);
116 if (ret == WAIT_OBJECT_0) {
119 assert(ret == WAIT_TIMEOUT);
123 # if defined(__MACH__) && defined(__APPLE__)
124 mach_timespec_t wait_time;
125 wait_time.tv_sec = time_ms / 1000;
126 wait_time.tv_nsec = 1000000 * (time_ms % 1000);
129 int ret = semaphore_timedwait(semaphore, wait_time);
131 case KERN_OPERATION_TIMED_OUT:
142 struct timespec wait_time;
145 if (gettimeofday(&now, NULL) == -1) {
146 std::cerr << "Semaphore::wait(ms): Unable to get time with gettimeofday!" << std::endl;
150 wait_time.tv_nsec = ((time_ms % 1000) * 1000 * 1000) + (now.tv_usec * 1000);
151 wait_time.tv_sec = (time_ms / 1000) + (wait_time.tv_nsec / (1000 * 1000 * 1000)) + now.tv_sec;
152 wait_time.tv_nsec %= 1000 * 1000 * 1000;
154 int ret = sem_timedwait(&semaphore, &wait_time);
157 assert(!ret || (errno == ETIMEDOUT || errno == EINTR));