dispatch_semaphore_create(3)

dispatch_semaphore_create3

Synchronized counting semaphore

Usage

#include <dispatch/dispatch.h>

dispatch_semaphore_t

dispatch_semaphore_create(long count);

long

dispatch_semaphore_signal(dispatch_semaphore_t semaphore);

long

dispatch_semaphore_wait(dispatch_semaphore_t semaphore, dispatch_time_t timeout);

Overview

Dispatch semaphores are used to synchronize threads.

The dispatch_semaphore_wait() 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 dispatch_semaphore_signal() before returning. The timeout parameter is creatable with the dispatch_time(3) or dispatch_walltime(3) functions. If the timeout is reached without a signal being received, the semaphore is re-incremented before the function returns.

The dispatch_semaphore_signal() function increments the counting semaphore. If the previous value was less than zero, it wakes one of the threads that are waiting in dispatch_semaphore_wait() before returning.

Completion synchronization

If the count 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);

Finite resource pool

If the count 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);

Return values

The dispatch_semaphore_create() function returns NULL if no memory is available or if the count parameter is less than zero.

The dispatch_semaphore_signal() function returns non-zero when a thread is woken. Otherwise, zero is returned.

The dispatch_semaphore_wait() function returns zero upon success and non-zero after the timeout expires. If the timeout is DISPATCH_TIME_FOREVER, then dispatch_semaphore_wait() waits forever and always returns zero.

Memory model

Dispatch semaphores are retained and released via calls to dispatch_retain() and dispatch_release().

Caveats

Unbalanced dispatch semaphores cannot be released. For a given semaphore, calls to dispatch_semaphore_signal() and dispatch_semaphore_wait() must be balanced before dispatch_release() is called on it.

Releases

4 releases since Debian 6.0 (Squeeze); the text changed 1 time.

  1. 6.0–8
  2. Arch

From libdispatch 6.2.2-1 in Arch Linux 2026-11-01. Parsed by carta from the page's mdoc source.