RavEngine
Loading...
Searching...
No Matches
lightweightsemaphore.h
1// Provides an efficient implementation of a semaphore (LightweightSemaphore).
2// This is an extension of Jeff Preshing's sempahore implementation (licensed
3// under the terms of its separate zlib license) that has been adapted and
4// extended by Cameron Desrochers.
5
6#pragma once
7
8#include <cstddef> // For std::size_t
9#include <atomic>
10#include <type_traits> // For std::make_signed<T>
11
12#if defined(_WIN32)
13// Avoid including windows.h in a header; we only need a handful of
14// items, so we'll redeclare them here (this is relatively safe since
15// the API generally has to remain stable between Windows versions).
16// I know this is an ugly hack but it still beats polluting the global
17// namespace with thousands of generic names or adding a .cpp for nothing.
18extern "C" {
19 struct _SECURITY_ATTRIBUTES;
20 __declspec(dllimport) void* __stdcall CreateSemaphoreW(_SECURITY_ATTRIBUTES* lpSemaphoreAttributes, long lInitialCount, long lMaximumCount, const wchar_t* lpName);
21 __declspec(dllimport) int __stdcall CloseHandle(void* hObject);
22 __declspec(dllimport) unsigned long __stdcall WaitForSingleObject(void* hHandle, unsigned long dwMilliseconds);
23 __declspec(dllimport) int __stdcall ReleaseSemaphore(void* hSemaphore, long lReleaseCount, long* lpPreviousCount);
24}
25#elif defined(__MACH__)
26#include <mach/mach.h>
27#elif defined(__unix__)
28#include <semaphore.h>
29#endif
30
31namespace moodycamel
32{
33namespace details
34{
35
36// Code in the mpmc_sema namespace below is an adaptation of Jeff Preshing's
37// portable + lightweight semaphore implementations, originally from
38// https://github.com/preshing/cpp11-on-multicore/blob/master/common/sema.h
39// LICENSE:
40// Copyright (c) 2015 Jeff Preshing
41//
42// This software is provided 'as-is', without any express or implied
43// warranty. In no event will the authors be held liable for any damages
44// arising from the use of this software.
45//
46// Permission is granted to anyone to use this software for any purpose,
47// including commercial applications, and to alter it and redistribute it
48// freely, subject to the following restrictions:
49//
50// 1. The origin of this software must not be misrepresented; you must not
51// claim that you wrote the original software. If you use this software
52// in a product, an acknowledgement in the product documentation would be
53// appreciated but is not required.
54// 2. Altered source versions must be plainly marked as such, and must not be
55// misrepresented as being the original software.
56// 3. This notice may not be removed or altered from any source distribution.
57#if defined(_WIN32)
58class Semaphore
59{
60private:
61 void* m_hSema;
62
63 Semaphore(const Semaphore& other) MOODYCAMEL_DELETE_FUNCTION;
64 Semaphore& operator=(const Semaphore& other) MOODYCAMEL_DELETE_FUNCTION;
65
66public:
67 Semaphore(int initialCount = 0)
68 {
69 assert(initialCount >= 0);
70 const long maxLong = 0x7fffffff;
71 m_hSema = CreateSemaphoreW(nullptr, initialCount, maxLong, nullptr);
72 assert(m_hSema);
73 }
74
75 ~Semaphore()
76 {
77 CloseHandle(m_hSema);
78 }
79
80 bool wait()
81 {
82 const unsigned long infinite = 0xffffffff;
83 return WaitForSingleObject(m_hSema, infinite) == 0;
84 }
85
86 bool try_wait()
87 {
88 return WaitForSingleObject(m_hSema, 0) == 0;
89 }
90
91 bool timed_wait(std::uint64_t usecs)
92 {
93 return WaitForSingleObject(m_hSema, (unsigned long)(usecs / 1000)) == 0;
94 }
95
96 void signal(int count = 1)
97 {
98 while (!ReleaseSemaphore(m_hSema, count, nullptr));
99 }
100};
101#elif defined(__MACH__)
102//---------------------------------------------------------
103// Semaphore (Apple iOS and OSX)
104// Can't use POSIX semaphores due to http://lists.apple.com/archives/darwin-kernel/2009/Apr/msg00010.html
105//---------------------------------------------------------
106class Semaphore
107{
108private:
109 semaphore_t m_sema;
110
111 Semaphore(const Semaphore& other) MOODYCAMEL_DELETE_FUNCTION;
112 Semaphore& operator=(const Semaphore& other) MOODYCAMEL_DELETE_FUNCTION;
113
114public:
115 Semaphore(int initialCount = 0)
116 {
117 assert(initialCount >= 0);
118 kern_return_t rc = semaphore_create(mach_task_self(), &m_sema, SYNC_POLICY_FIFO, initialCount);
119 assert(rc == KERN_SUCCESS);
120 (void)rc;
121 }
122
123 ~Semaphore()
124 {
125 semaphore_destroy(mach_task_self(), m_sema);
126 }
127
128 bool wait()
129 {
130 return semaphore_wait(m_sema) == KERN_SUCCESS;
131 }
132
133 bool try_wait()
134 {
135 return timed_wait(0);
136 }
137
138 bool timed_wait(std::uint64_t timeout_usecs)
139 {
140 mach_timespec_t ts;
141 ts.tv_sec = static_cast<unsigned int>(timeout_usecs / 1000000);
142 ts.tv_nsec = static_cast<int>((timeout_usecs % 1000000) * 1000);
143
144 // added in OSX 10.10: https://developer.apple.com/library/prerelease/mac/documentation/General/Reference/APIDiffsMacOSX10_10SeedDiff/modules/Darwin.html
145 kern_return_t rc = semaphore_timedwait(m_sema, ts);
146 return rc == KERN_SUCCESS;
147 }
148
149 void signal()
150 {
151 while (semaphore_signal(m_sema) != KERN_SUCCESS);
152 }
153
154 void signal(int count)
155 {
156 while (count-- > 0)
157 {
158 while (semaphore_signal(m_sema) != KERN_SUCCESS);
159 }
160 }
161};
162#elif defined(__unix__)
163//---------------------------------------------------------
164// Semaphore (POSIX, Linux)
165//---------------------------------------------------------
166class Semaphore
167{
168private:
169 sem_t m_sema;
170
171 Semaphore(const Semaphore& other) MOODYCAMEL_DELETE_FUNCTION;
172 Semaphore& operator=(const Semaphore& other) MOODYCAMEL_DELETE_FUNCTION;
173
174public:
175 Semaphore(int initialCount = 0)
176 {
177 assert(initialCount >= 0);
178 int rc = sem_init(&m_sema, 0, static_cast<unsigned int>(initialCount));
179 assert(rc == 0);
180 (void)rc;
181 }
182
183 ~Semaphore()
184 {
185 sem_destroy(&m_sema);
186 }
187
188 bool wait()
189 {
190 // http://stackoverflow.com/questions/2013181/gdb-causes-sem-wait-to-fail-with-eintr-error
191 int rc;
192 do {
193 rc = sem_wait(&m_sema);
194 } while (rc == -1 && errno == EINTR);
195 return rc == 0;
196 }
197
198 bool try_wait()
199 {
200 int rc;
201 do {
202 rc = sem_trywait(&m_sema);
203 } while (rc == -1 && errno == EINTR);
204 return rc == 0;
205 }
206
207 bool timed_wait(std::uint64_t usecs)
208 {
209 struct timespec ts;
210 const int usecs_in_1_sec = 1000000;
211 const int nsecs_in_1_sec = 1000000000;
212 clock_gettime(CLOCK_REALTIME, &ts);
213 ts.tv_sec += (time_t)(usecs / usecs_in_1_sec);
214 ts.tv_nsec += (long)(usecs % usecs_in_1_sec) * 1000;
215 // sem_timedwait bombs if you have more than 1e9 in tv_nsec
216 // so we have to clean things up before passing it in
217 if (ts.tv_nsec >= nsecs_in_1_sec) {
218 ts.tv_nsec -= nsecs_in_1_sec;
219 ++ts.tv_sec;
220 }
221
222 int rc;
223 do {
224 rc = sem_timedwait(&m_sema, &ts);
225 } while (rc == -1 && errno == EINTR);
226 return rc == 0;
227 }
228
229 void signal()
230 {
231 while (sem_post(&m_sema) == -1);
232 }
233
234 void signal(int count)
235 {
236 while (count-- > 0)
237 {
238 while (sem_post(&m_sema) == -1);
239 }
240 }
241};
242#else
243#error Unsupported platform! (No semaphore wrapper available)
244#endif
245
246} // end namespace details
247
248
249//---------------------------------------------------------
250// LightweightSemaphore
251//---------------------------------------------------------
253{
254public:
255 typedef std::make_signed<std::size_t>::type ssize_t;
256
257private:
258 std::atomic<ssize_t> m_count;
259 details::Semaphore m_sema;
260 int m_maxSpins;
261
262 bool waitWithPartialSpinning(std::int64_t timeout_usecs = -1)
263 {
264 ssize_t oldCount;
265 int spin = m_maxSpins;
266 while (--spin >= 0)
267 {
268 oldCount = m_count.load(std::memory_order_relaxed);
269 if ((oldCount > 0) && m_count.compare_exchange_strong(oldCount, oldCount - 1, std::memory_order_acquire, std::memory_order_relaxed))
270 return true;
271 std::atomic_signal_fence(std::memory_order_acquire); // Prevent the compiler from collapsing the loop.
272 }
273 oldCount = m_count.fetch_sub(1, std::memory_order_acquire);
274 if (oldCount > 0)
275 return true;
276 if (timeout_usecs < 0)
277 {
278 if (m_sema.wait())
279 return true;
280 }
281 if (timeout_usecs > 0 && m_sema.timed_wait((std::uint64_t)timeout_usecs))
282 return true;
283 // At this point, we've timed out waiting for the semaphore, but the
284 // count is still decremented indicating we may still be waiting on
285 // it. So we have to re-adjust the count, but only if the semaphore
286 // wasn't signaled enough times for us too since then. If it was, we
287 // need to release the semaphore too.
288 while (true)
289 {
290 oldCount = m_count.load(std::memory_order_acquire);
291 if (oldCount >= 0 && m_sema.try_wait())
292 return true;
293 if (oldCount < 0 && m_count.compare_exchange_strong(oldCount, oldCount + 1, std::memory_order_relaxed, std::memory_order_relaxed))
294 return false;
295 }
296 }
297
298 ssize_t waitManyWithPartialSpinning(ssize_t max, std::int64_t timeout_usecs = -1)
299 {
300 assert(max > 0);
301 ssize_t oldCount;
302 int spin = m_maxSpins;
303 while (--spin >= 0)
304 {
305 oldCount = m_count.load(std::memory_order_relaxed);
306 if (oldCount > 0)
307 {
308 ssize_t newCount = oldCount > max ? oldCount - max : 0;
309 if (m_count.compare_exchange_strong(oldCount, newCount, std::memory_order_acquire, std::memory_order_relaxed))
310 return oldCount - newCount;
311 }
312 std::atomic_signal_fence(std::memory_order_acquire);
313 }
314 oldCount = m_count.fetch_sub(1, std::memory_order_acquire);
315 if (oldCount <= 0)
316 {
317 if ((timeout_usecs == 0) || (timeout_usecs < 0 && !m_sema.wait()) || (timeout_usecs > 0 && !m_sema.timed_wait((std::uint64_t)timeout_usecs)))
318 {
319 while (true)
320 {
321 oldCount = m_count.load(std::memory_order_acquire);
322 if (oldCount >= 0 && m_sema.try_wait())
323 break;
324 if (oldCount < 0 && m_count.compare_exchange_strong(oldCount, oldCount + 1, std::memory_order_relaxed, std::memory_order_relaxed))
325 return 0;
326 }
327 }
328 }
329 if (max > 1)
330 return 1 + tryWaitMany(max - 1);
331 return 1;
332 }
333
334public:
335 LightweightSemaphore(ssize_t initialCount = 0, int maxSpins = 10000) : m_count(initialCount), m_maxSpins(maxSpins)
336 {
337 assert(initialCount >= 0);
338 assert(maxSpins >= 0);
339 }
340
341 bool tryWait()
342 {
343 ssize_t oldCount = m_count.load(std::memory_order_relaxed);
344 while (oldCount > 0)
345 {
346 if (m_count.compare_exchange_weak(oldCount, oldCount - 1, std::memory_order_acquire, std::memory_order_relaxed))
347 return true;
348 }
349 return false;
350 }
351
352 bool wait()
353 {
354 return tryWait() || waitWithPartialSpinning();
355 }
356
357 bool wait(std::int64_t timeout_usecs)
358 {
359 return tryWait() || waitWithPartialSpinning(timeout_usecs);
360 }
361
362 // Acquires between 0 and (greedily) max, inclusive
363 ssize_t tryWaitMany(ssize_t max)
364 {
365 assert(max >= 0);
366 ssize_t oldCount = m_count.load(std::memory_order_relaxed);
367 while (oldCount > 0)
368 {
369 ssize_t newCount = oldCount > max ? oldCount - max : 0;
370 if (m_count.compare_exchange_weak(oldCount, newCount, std::memory_order_acquire, std::memory_order_relaxed))
371 return oldCount - newCount;
372 }
373 return 0;
374 }
375
376 // Acquires at least one, and (greedily) at most max
377 ssize_t waitMany(ssize_t max, std::int64_t timeout_usecs)
378 {
379 assert(max >= 0);
380 ssize_t result = tryWaitMany(max);
381 if (result == 0 && max > 0)
382 result = waitManyWithPartialSpinning(max, timeout_usecs);
383 return result;
384 }
385
386 ssize_t waitMany(ssize_t max)
387 {
388 ssize_t result = waitMany(max, -1);
389 assert(result > 0);
390 return result;
391 }
392
393 void signal(ssize_t count = 1)
394 {
395 assert(count >= 0);
396 ssize_t oldCount = m_count.fetch_add(count, std::memory_order_release);
397 ssize_t toRelease = -oldCount < count ? -oldCount : count;
398 if (toRelease > 0)
399 {
400 m_sema.signal((int)toRelease);
401 }
402 }
403
404 std::size_t availableApprox() const
405 {
406 ssize_t count = m_count.load(std::memory_order_relaxed);
407 return count > 0 ? static_cast<std::size_t>(count) : 0;
408 }
409};
410
411} // end namespace moodycamel
Definition concurrentqueue.h:747
Definition lightweightsemaphore.h:253