What is DispatchSemaphore and what if you forget signal()?
The essence
DispatchSemaphore is GCD's counting semaphore. wait() decrements the counter and blocks the thread if it went negative; signal() increments it and wakes one waiter. DispatchSemaphore(value: N) limits a section to N threads; value: 0 is used to wait for an event.
If you forget signal(), the waiting thread never wakes up. The consequences depend on who waits:
- the main thread — the app freezes and the watchdog kills it after a few seconds;
- a GCD pool thread — the thread leaks forever; repeated, that means thread explosion and pool exhaustion;
- a Swift Concurrency cooperative pool thread — the pool is small (about one thread per core), a single blocked thread can already stall every task.
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep