Semaphore
The essence
A semaphore is a synchronization primitive with a counter. wait() decrements the counter and, if it went negative, blocks the thread until someone calls signal() (which increments the counter and wakes one waiter). A semaphore with value N lets at most N threads into the section at once; with an initial value of 0 it acts as an "event signal".
iOS has three API families:
- GCD:
DispatchSemaphore(value:),wait(),wait(timeout:),signal()— what interviewers mean. - POSIX:
sem_init,sem_wait,sem_post,sem_destroy. - Mach:
semaphore_create,semaphore_wait,semaphore_signal,semaphore_destroy— kernel level, not used in app code.
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep