1dispatch_semaphore_cr... BSD Library Functions Manual dispatch_semaphore_cr...
2
4 dispatch_semaphore_create, dispatch_semaphore_signal,
5 dispatch_semaphore_wait — synchronized counting semaphore
6
8 #include <dispatch/dispatch.h>
9
10 dispatch_semaphore_t
11 dispatch_semaphore_create(long count);
12
13 long
14 dispatch_semaphore_signal(dispatch_semaphore_t semaphore);
15
16 long
17 dispatch_semaphore_wait(dispatch_semaphore_t semaphore,
18 dispatch_time_t timeout);
19
21 Dispatch semaphores are used to synchronize threads.
22
23 The dispatch_semaphore_wait() function decrements the semaphore. If the
24 resulting value is less than zero, it waits for a signal from a thread
25 that increments the semaphore by calling dispatch_semaphore_signal()
26 before returning. The timeout parameter is creatable with the
27 dispatch_time(3) or dispatch_walltime(3) functions. If the timeout is
28 reached without a signal being received, the semaphore is re-incremented
29 before the function returns.
30
31 The dispatch_semaphore_signal() function increments the counting sema‐
32 phore. If the previous value was less than zero, it wakes one of the
33 threads that are waiting in dispatch_semaphore_wait() before returning.
34
36 If the count parameter is equal to zero, then the semaphore is useful for
37 synchronizing completion of work. For example:
38
39 sema = dispatch_semaphore_create(0);
40
41 dispatch_async(queue, ^{
42 foo();
43 dispatch_semaphore_signal(sema);
44 });
45
46 bar();
47
48 dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
49
51 If the count parameter is greater than zero, then the semaphore is useful
52 for managing a finite pool of resources. For example, a library that
53 wants to limit Unix descriptor usage:
54
55 sema = dispatch_semaphore_create(getdtablesize() / 4);
56
57 At each Unix FD allocation:
58
59 dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
60 fd = open("/etc/services", O_RDONLY);
61
62 When each FD is closed:
63
64 close(fd);
65 dispatch_semaphore_signal(sema);
66
68 The dispatch_semaphore_create() function returns NULL if no memory is
69 available or if the count parameter is less than zero.
70
71 The dispatch_semaphore_signal() function returns non-zero when a thread
72 is woken. Otherwise, zero is returned.
73
74 The dispatch_semaphore_wait() function returns zero upon success and non-
75 zero after the timeout expires. If the timeout is DISPATCH_TIME_FOREVER,
76 then dispatch_semaphore_wait() waits forever and always returns zero.
77
79 Dispatch semaphores are retained and released via calls to
80 dispatch_retain() and dispatch_release().
81
83 Unbalanced dispatch semaphores cannot be released. For a given sema‐
84 phore, calls to dispatch_semaphore_signal() and dispatch_semaphore_wait()
85 must be balanced before dispatch_release() is called on it.
86
88 dispatch(3), dispatch_object(3)
89
90Darwin May 1, 2009 Darwin