Manpages - dispatch_semaphore_create.3
Dispatch semaphores are used to synchronize threads.
The
function decrements the semaphore. If the resulting value is less than zero, it waits for a signal from a thread that increments the semaphore by calling
before returning. The
parameter is creatable with the
or
functions. If the timeout is reached without a signal being received, the semaphore is re-incremented before the function returns.
The
function increments the counting semaphore. If the previous value was less than zero, it wakes one of the threads that are waiting in
before returning.
If the
parameter is equal to zero, then the semaphore is useful for synchronizing completion of work. For example:
sema = dispatch_semaphore_create(0);
dispatch_async(queue, ^{ foo(); dispatch_semaphore_signal(sema); });
bar();
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
If the
parameter is greater than zero, then the semaphore is useful for managing a finite pool of resources. For example, a library that wants to limit Unix descriptor usage:
sema = dispatch_semaphore_create(getdtablesize() / 4);
At each Unix FD allocation:
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); fd = open(“/etc/services”, O_RDONLY);
When each FD is closed:
close(fd); dispatch_semaphore_signal(sema);
The
function returns NULL if no memory is available or if the
parameter is less than zero.
The
function returns non-zero when a thread is woken. Otherwise, zero is returned.
The
function returns zero upon success and non-zero after the timeout expires. If the timeout is DISPATCH_TIME_FOREVER, then
waits forever and always returns zero.
Dispatch semaphores are retained and released via calls to
and
Unbalanced dispatch semaphores cannot be released. For a given semaphore, calls to
and
must be balanced before
is called on it.