Debian Codegraph @

libphobos/libdruntime/core/sync/semaphore.d

raw
1 /**
2 * The semaphore module provides a general use semaphore for synchronization.
3 *
4 * Copyright: Copyright Sean Kelly 2005 - 2009.
5 * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
6 * Authors: Sean Kelly
7 * Source: $(DRUNTIMESRC core/sync/_semaphore.d)
8 */
9
10 /* Copyright Sean Kelly 2005 - 2009.
11 * Distributed under the Boost Software License, Version 1.0.
12 * (See accompanying file LICENSE or copy at
13 * http://www.boost.org/LICENSE_1_0.txt)
14 */
15 module core.sync.semaphore;
16
17
18 public import core.sync.exception;
19 public import core.time;
20
21 version (OSX)
22 version = Darwin;
23 else version (iOS)
24 version = Darwin;
25 else version (TVOS)
26 version = Darwin;
27 else version (WatchOS)
28 version = Darwin;
29
30 version (Windows)
31 {
32 import core.sys.windows.basetsd /+: HANDLE+/;
33 import core.sys.windows.winbase /+: CloseHandle, CreateSemaphoreA, INFINITE,
34 ReleaseSemaphore, WAIT_OBJECT_0, WaitForSingleObject+/;
35 import core.sys.windows.windef /+: BOOL, DWORD+/;
36 import core.sys.windows.winerror /+: WAIT_TIMEOUT+/;
37 }
38 else version (Darwin)
39 {
40 import core.stdc.errno : EINTR, errno;
41 import core.sync.config;
42 import core.sys.darwin.mach.kern_return : KERN_ABORTED, KERN_OPERATION_TIMED_OUT;
43 import core.sys.darwin.mach.semaphore : mach_task_self, mach_timespec_t, semaphore_create, semaphore_destroy,
44 semaphore_signal, semaphore_t, semaphore_timedwait, semaphore_wait, SYNC_POLICY_FIFO;
45 }
46 else version (Posix)
47 {
48 import core.stdc.errno : EAGAIN, EINTR, errno, ETIMEDOUT;
49 import core.sync.config;
50 import core.sys.posix.semaphore : sem_destroy, sem_init, sem_post, sem_t, sem_timedwait, sem_trywait, sem_wait;
51 import core.sys.posix.time : clock_gettime, CLOCK_REALTIME, timespec;
52 }
53 else
54 {
55 static assert(false, "Platform not supported");
56 }
57
58
59 ////////////////////////////////////////////////////////////////////////////////
60 // Semaphore
61 //
62 // void wait();
63 // void notify();
64 // bool tryWait();
65 ////////////////////////////////////////////////////////////////////////////////
66
67
68 /**
69 * This class represents a general counting semaphore as concieved by Edsger
70 * Dijkstra. As per Mesa type monitors however, "signal" has been replaced
71 * with "notify" to indicate that control is not transferred to the waiter when
72 * a notification is sent.
73 */
74 class Semaphore
75 {
76 ////////////////////////////////////////////////////////////////////////////
77 // Initialization
78 ////////////////////////////////////////////////////////////////////////////
79
80
81 /**
82 * Initializes a semaphore object with the specified initial count.
83 *
84 * Params:
85 * count = The initial count for the semaphore.
86 *
87 * Throws:
88 * SyncError on error.
89 */
90 this( uint count = 0 )
91 {
92 version (Windows)
93 {
94 m_hndl = CreateSemaphoreA( null, count, int.max, null );
95 if ( m_hndl == m_hndl.init )
96 throw new SyncError( "Unable to create semaphore" );
97 }
98 else version (Darwin)
99 {
100 auto rc = semaphore_create( mach_task_self(), &m_hndl, SYNC_POLICY_FIFO, count );
101 if ( rc )
102 throw new SyncError( "Unable to create semaphore" );
103 }
104 else version (Posix)
105 {
106 int rc = sem_init( &m_hndl, 0, count );
107 if ( rc )
108 throw new SyncError( "Unable to create semaphore" );
109 }
110 }
111
112
113 ~this()
114 {
115 version (Windows)
116 {
117 BOOL rc = CloseHandle( m_hndl );
118 assert( rc, "Unable to destroy semaphore" );
119 }
120 else version (Darwin)
121 {
122 auto rc = semaphore_destroy( mach_task_self(), m_hndl );
123 assert( !rc, "Unable to destroy semaphore" );
124 }
125 else version (Posix)
126 {
127 int rc = sem_destroy( &m_hndl );
128 assert( !rc, "Unable to destroy semaphore" );
129 }
130 }
131
132
133 ////////////////////////////////////////////////////////////////////////////
134 // General Actions
135 ////////////////////////////////////////////////////////////////////////////
136
137
138 /**
139 * Wait until the current count is above zero, then atomically decrement
140 * the count by one and return.
141 *
142 * Throws:
143 * SyncError on error.
144 */
145 void wait()
146 {
147 version (Windows)
148 {
149 DWORD rc = WaitForSingleObject( m_hndl, INFINITE );
150 if ( rc != WAIT_OBJECT_0 )
151 throw new SyncError( "Unable to wait for semaphore" );
152 }
153 else version (Darwin)
154 {
155 while ( true )
156 {
157 auto rc = semaphore_wait( m_hndl );
158 if ( !rc )
159 return;
160 if ( rc == KERN_ABORTED && errno == EINTR )
161 continue;
162 throw new SyncError( "Unable to wait for semaphore" );
163 }
164 }
165 else version (Posix)
166 {
167 while ( true )
168 {
169 if ( !sem_wait( &m_hndl ) )
170 return;
171 if ( errno != EINTR )
172 throw new SyncError( "Unable to wait for semaphore" );
173 }
174 }
175 }
176
177
178 /**
179 * Suspends the calling thread until the current count moves above zero or
180 * until the supplied time period has elapsed. If the count moves above
181 * zero in this interval, then atomically decrement the count by one and
182 * return true. Otherwise, return false.
183 *
184 * Params:
185 * period = The time to wait.
186 *
187 * In:
188 * period must be non-negative.
189 *
190 * Throws:
191 * SyncError on error.
192 *
193 * Returns:
194 * true if notified before the timeout and false if not.
195 */
196 bool wait( Duration period )
197 in
198 {
199 assert( !period.isNegative );
200 }
201 do
202 {
203 version (Windows)
204 {
205 auto maxWaitMillis = dur!("msecs")( uint.max - 1 );
206
207 while ( period > maxWaitMillis )
208 {
209 auto rc = WaitForSingleObject( m_hndl, cast(uint)
210 maxWaitMillis.total!"msecs" );
211 switch ( rc )
212 {
213 case WAIT_OBJECT_0:
214 return true;
215 case WAIT_TIMEOUT:
216 period -= maxWaitMillis;
217 continue;
218 default:
219 throw new SyncError( "Unable to wait for semaphore" );
220 }
221 }
222 switch ( WaitForSingleObject( m_hndl, cast(uint) period.total!"msecs" ) )
223 {
224 case WAIT_OBJECT_0:
225 return true;
226 case WAIT_TIMEOUT:
227 return false;
228 default:
229 throw new SyncError( "Unable to wait for semaphore" );
230 }
231 }
232 else version (Darwin)
233 {
234 mach_timespec_t t = void;
235 (cast(byte*) &t)[0 .. t.sizeof] = 0;
236
237 if ( period.total!"seconds" > t.tv_sec.max )
238 {
239 t.tv_sec = t.tv_sec.max;
240 t.tv_nsec = cast(typeof(t.tv_nsec)) period.split!("seconds", "nsecs")().nsecs;
241 }
242 else
243 period.split!("seconds", "nsecs")(t.tv_sec, t.tv_nsec);
244 while ( true )
245 {
246 auto rc = semaphore_timedwait( m_hndl, t );
247 if ( !rc )
248 return true;
249 if ( rc == KERN_OPERATION_TIMED_OUT )
250 return false;
251 if ( rc != KERN_ABORTED || errno != EINTR )
252 throw new SyncError( "Unable to wait for semaphore" );
253 }
254 }
255 else version (Posix)
256 {
257 timespec t = void;
258 clock_gettime( CLOCK_REALTIME, &t );
259 mvtspec( t, period );
260
261 while ( true )
262 {
263 if ( !sem_timedwait( &m_hndl, &t ) )
264 return true;
265 if ( errno == ETIMEDOUT )
266 return false;
267 if ( errno != EINTR )
268 throw new SyncError( "Unable to wait for semaphore" );
269 }
270 }
271 }
272
273
274 /**
275 * Atomically increment the current count by one. This will notify one
276 * waiter, if there are any in the queue.
277 *
278 * Throws:
279 * SyncError on error.
280 */
281 void notify()
282 {
283 version (Windows)
284 {
285 if ( !ReleaseSemaphore( m_hndl, 1, null ) )
286 throw new SyncError( "Unable to notify semaphore" );
287 }
288 else version (Darwin)
289 {
290 auto rc = semaphore_signal( m_hndl );
291 if ( rc )
292 throw new SyncError( "Unable to notify semaphore" );
293 }
294 else version (Posix)
295 {
296 int rc = sem_post( &m_hndl );
297 if ( rc )
298 throw new SyncError( "Unable to notify semaphore" );
299 }
300 }
301
302
303 /**
304 * If the current count is equal to zero, return. Otherwise, atomically
305 * decrement the count by one and return true.
306 *
307 * Throws:
308 * SyncError on error.
309 *
310 * Returns:
311 * true if the count was above zero and false if not.
312 */
313 bool tryWait()
314 {
315 version (Windows)
316 {
317 switch ( WaitForSingleObject( m_hndl, 0 ) )
318 {
319 case WAIT_OBJECT_0:
320 return true;
321 case WAIT_TIMEOUT:
322 return false;
323 default:
324 throw new SyncError( "Unable to wait for semaphore" );
325 }
326 }
327 else version (Darwin)
328 {
329 return wait( dur!"hnsecs"(0) );
330 }
331 else version (Posix)
332 {
333 while ( true )
334 {
335 if ( !sem_trywait( &m_hndl ) )
336 return true;
337 if ( errno == EAGAIN )
338 return false;
339 if ( errno != EINTR )
340 throw new SyncError( "Unable to wait for semaphore" );
341 }
342 }
343 }
344
345
346 protected:
347
348 /// Aliases the operating-system-specific semaphore type.
349 version (Windows) alias Handle = HANDLE;
350 /// ditto
351 else version (Darwin) alias Handle = semaphore_t;
352 /// ditto
353 else version (Posix) alias Handle = sem_t;
354
355 /// Handle to the system-specific semaphore.
356 Handle m_hndl;
357 }
358
359
360 ////////////////////////////////////////////////////////////////////////////////
361 // Unit Tests
362 ////////////////////////////////////////////////////////////////////////////////
363
364 unittest
365 {
366 import core.atomic;
367 import core.thread;
368
369 void testWait()
370 {
371 auto semaphore = new Semaphore;
372 shared bool stopConsumption = false;
373 immutable numToProduce = 20;
374 immutable numConsumers = 10;
375 shared size_t numConsumed;
376 shared size_t numComplete;
377
378 void consumer()
379 {
380 while (true)
381 {
382 semaphore.wait();
383
384 if (atomicLoad(stopConsumption))
385 break;
386 atomicOp!"+="(numConsumed, 1);
387 }
388 atomicOp!"+="(numComplete, 1);
389 }
390
391 void producer()
392 {
393 assert(!semaphore.tryWait());
394
395 foreach (_; 0 .. numToProduce)
396 semaphore.notify();
397
398 // wait until all items are consumed
399 while (atomicLoad(numConsumed) != numToProduce)
400 Thread.yield();
401
402 // mark consumption as finished
403 atomicStore(stopConsumption, true);
404
405 // wake all consumers
406 foreach (_; 0 .. numConsumers)
407 semaphore.notify();
408
409 // wait until all consumers completed
410 while (atomicLoad(numComplete) != numConsumers)
411 Thread.yield();
412
413 assert(!semaphore.tryWait());
414 semaphore.notify();
415 assert(semaphore.tryWait());
416 assert(!semaphore.tryWait());
417 }
418
419 auto group = new ThreadGroup;
420
421 for ( int i = 0; i < numConsumers; ++i )
422 group.create(&consumer);
423 group.create(&producer);
424 group.joinAll();
425 }
426
427
428 void testWaitTimeout()
429 {
430 auto sem = new Semaphore;
431 shared bool semReady;
432 bool alertedOne, alertedTwo;
433
434 void waiter()
435 {
436 while (!atomicLoad(semReady))
437 Thread.yield();
438 alertedOne = sem.wait(dur!"msecs"(1));
439 alertedTwo = sem.wait(dur!"msecs"(1));
440 assert(alertedOne && !alertedTwo);
441 }
442
443 auto thread = new Thread(&waiter);
444 thread.start();
445
446 sem.notify();
447 atomicStore(semReady, true);
448 thread.join();
449 assert(alertedOne && !alertedTwo);
450 }
451
452 testWait();
453 testWaitTimeout();
454 }