Next: Global Variable Namespaces Up: Threads and Namespaces Previous: Thread Utilities

# Semaphores

A semaphore is a value that is used to synchronize MzScheme threads. Each semaphore has an internal counter; when this counter is zero, the semaphore can block a thread's execution (through `semaphore-wait`) until another thread increments the counter (using `semaphore-post`). The maximum value for a semaphore's internal counter is platform-specific, but always at least 10000. MzScheme's semaphores have the usual single-threaded access for reliable synchronization.

- `(make-semaphore [init-k])` creates and returns a new semaphore with the counter initially set to init-k, which defaults to `0`. If init-k is larger than a semaphore's maximum internal counter value, the `exn:application:mismatch` exception is raised.
- `(semaphore? v)` returns `#t` if v is a semaphore created by `make-semaphore`, `#f` otherwise.
- `(semaphore-post sema)` increments the semaphore's internal counter and returns void. If the semaphore's internal counter has already reached its maximum value, the `exn:misc` exception is raised.
- `(semaphore-wait sema)` blocks until the internal counter for semaphore sema is non-zero. When the counter is non-zero, it is decremented and `semaphore-wait` returns void.
- `(semaphore-try-wait? sema)` is like `semaphore-wait`, but `semaphore-try-wait?` never blocks execution. If sema's internal counter is zero, `semaphore-try-wait?` returns `#f` immediately without decrementing the counter. If sema's counter is positive, it is decremented and `#t` is returned.
- `(semaphore-wait/enable-break sema)` is like `semaphore-wait`, but breaking is enabled (see section 8.6) while waiting on sema. If breaking is disabled when `semaphore-wait/enable-break` is called, then either the semaphore's counter is decremented or the `exn:misc:user-break` exception is raised, but not both.