1 .\" Copyright (c) 2008-2009 Apple Inc. All rights reserved.
3 .Dt dispatch_semaphore_create 3
6 .Nm dispatch_semaphore_create ,
7 .Nm dispatch_semaphore_signal ,
8 .Nm dispatch_semaphore_wait
9 .Nd synchronized counting semaphore
11 .Fd #include <dispatch/dispatch.h>
12 .Ft dispatch_semaphore_t
13 .Fo dispatch_semaphore_create
17 .Fo dispatch_semaphore_signal
18 .Fa "dispatch_semaphore_t semaphore"
21 .Fo dispatch_semaphore_wait
22 .Fa "dispatch_semaphore_t semaphore" "dispatch_time_t timeout"
25 Dispatch semaphores are used to synchronize threads.
28 parameter is creatable with the
31 .Xr dispatch_walltime 3
33 .Sh COMPLETION SYNCHRONIZATION
36 parameter is equal to zero, then the semaphore is useful for synchronizing completion of work.
38 .Bd -literal -offset indent
39 sema = dispatch_semaphore_create(0);
41 dispatch_async(queue, ^{
43 dispatch_semaphore_signal(sema);
48 dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
50 .Sh FINITE RESOURCE POOL
53 parameter is greater than zero, then the semaphore is useful for managing a finite pool of resources.
54 For example, a library that wants to limit Unix descriptor usage:
55 .Bd -literal -offset indent
56 sema = dispatch_semaphore_create(getdtablesize() / 4);
59 At each Unix FD allocation:
60 .Bd -literal -offset indent
61 dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
62 fd = open("/etc/services", O_RDONLY);
65 When each FD is closed:
66 .Bd -literal -offset indent
68 dispatch_semaphore_signal(sema);
72 .Fn dispatch_semaphore_create
73 function returns NULL if no memory is available or if the
75 parameter is less than zero.
78 .Fn dispatch_semaphore_signal
79 function returns non-zero when a thread is woken.
80 Otherwise, zero is returned.
83 .Fn dispatch_semaphore_wait
84 function returns zero upon success and non-zero after the timeout expires. If the timeout is DISPATCH_TIME_FOREVER, then
85 .Fn dispatch_semaphore_wait
86 waits forever and always returns zero.
88 Dispatch semaphores are retained and released via calls to
91 .Fn dispatch_release .
93 Dispatch semaphores are strict counting semaphores.
94 In other words, dispatch semaphores do not saturate at any particular value.
95 Saturation can be achieved through atomic compare-and-swap logic.
96 What follows is a saturating binary semaphore:
99 saturating_semaphore_signal(dispatch_semaphore_t dsema, int *sent)
101 if (__sync_bool_compare_and_swap(sent, 0, 1)) {
102 dispatch_semaphore_signal(dsema);
107 saturating_semaphore_wait(dispatch_semaphore_t dsema, int *sent)
110 dispatch_semaphore_wait(dsema, DISPATCH_TIME_FOREVER);
114 .Xr dispatch_object 3