1 .\" Copyright (c) 2008-2012 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 .Fn dispatch_semaphore_wait
29 function decrements the semaphore. If the resulting value is less than zero,
30 it waits for a signal from a thread that increments the semaphore by calling
31 .Fn dispatch_semaphore_signal
35 parameter is creatable with the
38 .Xr dispatch_walltime 3
42 .Fn dispatch_semaphore_signal
43 function increments the counting semaphore. If the previous value was less than zero,
44 it wakes one of the threads that are waiting in
45 .Fn dispatch_semaphore_wait
47 .Sh COMPLETION SYNCHRONIZATION
50 parameter is equal to zero, then the semaphore is useful for synchronizing
53 .Bd -literal -offset indent
54 sema = dispatch_semaphore_create(0);
56 dispatch_async(queue, ^{
58 dispatch_semaphore_signal(sema);
63 dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
65 .Sh FINITE RESOURCE POOL
68 parameter is greater than zero, then the semaphore is useful for managing a
69 finite pool of resources.
70 For example, a library that wants to limit Unix descriptor usage:
71 .Bd -literal -offset indent
72 sema = dispatch_semaphore_create(getdtablesize() / 4);
75 At each Unix FD allocation:
76 .Bd -literal -offset indent
77 dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
78 fd = open("/etc/services", O_RDONLY);
81 When each FD is closed:
82 .Bd -literal -offset indent
84 dispatch_semaphore_signal(sema);
88 .Fn dispatch_semaphore_create
89 function returns NULL if no memory is available or if the
91 parameter is less than zero.
94 .Fn dispatch_semaphore_signal
95 function returns non-zero when a thread is woken.
96 Otherwise, zero is returned.
99 .Fn dispatch_semaphore_wait
100 function returns zero upon success and non-zero after the timeout expires. If
101 the timeout is DISPATCH_TIME_FOREVER, then
102 .Fn dispatch_semaphore_wait
103 waits forever and always returns zero.
105 Dispatch semaphores are retained and released via calls to
108 .Fn dispatch_release .
110 Unbalanced dispatch semaphores cannot be released.
111 For a given semaphore, calls to
112 .Fn dispatch_semaphore_signal
114 .Fn dispatch_semaphore_wait
115 must be balanced before
120 .Xr dispatch_object 3