1 .\" Copyright (c) 2008-2010 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
39 .Bd -literal -offset indent
40 sema = dispatch_semaphore_create(0);
42 dispatch_async(queue, ^{
44 dispatch_semaphore_signal(sema);
49 dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
51 .Sh FINITE RESOURCE POOL
54 parameter is greater than zero, then the semaphore is useful for managing a
55 finite pool of resources.
56 For example, a library that wants to limit Unix descriptor usage:
57 .Bd -literal -offset indent
58 sema = dispatch_semaphore_create(getdtablesize() / 4);
61 At each Unix FD allocation:
62 .Bd -literal -offset indent
63 dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
64 fd = open("/etc/services", O_RDONLY);
67 When each FD is closed:
68 .Bd -literal -offset indent
70 dispatch_semaphore_signal(sema);
74 .Fn dispatch_semaphore_create
75 function returns NULL if no memory is available or if the
77 parameter is less than zero.
80 .Fn dispatch_semaphore_signal
81 function returns non-zero when a thread is woken.
82 Otherwise, zero is returned.
85 .Fn dispatch_semaphore_wait
86 function returns zero upon success and non-zero after the timeout expires. If
87 the timeout is DISPATCH_TIME_FOREVER, then
88 .Fn dispatch_semaphore_wait
89 waits forever and always returns zero.
91 Dispatch semaphores are retained and released via calls to
94 .Fn dispatch_release .
96 Unbalanced dispatch semaphores cannot be released.
97 For a given semaphore, calls to
98 .Fn dispatch_semaphore_signal
100 .Fn dispatch_semaphore_wait
101 must be balanced before
105 Dispatch semaphores are strict counting semaphores.
106 In other words, dispatch semaphores do not saturate at any particular value.
107 Saturation can be achieved through atomic compare-and-swap logic.
108 What follows is a saturating binary semaphore:
111 saturating_semaphore_signal(dispatch_semaphore_t dsema, int *sent)
113 if (__sync_bool_compare_and_swap(sent, 0, 1)) {
114 dispatch_semaphore_signal(dsema);
119 saturating_semaphore_wait(dispatch_semaphore_t dsema, int *sent)
122 dispatch_semaphore_wait(dsema, DISPATCH_TIME_FOREVER);
127 .Xr dispatch_object 3