DevPrep

All topics › Multithreading & concurrency

What is DispatchSemaphore and what if you forget signal()?

Middle PRO

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 rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store