Junior — Middle
Could you explain what a semaphore is and how it is used for process synchronization?
sobes.tech AI
Answer from AI
A semaphore is a synchronization mechanism used to control access to a shared resource in a multithreaded or multiprocess environment. It contains a counter that indicates how many threads or processes can access the resource simultaneously.
Working principle:
- Initially, the semaphore counter is set to the number of available resources.
- When a thread wants to access the resource, it calls the
wait(oracquire) operation, which decreases the counter. - If the counter becomes less than zero, the thread is blocked, waiting for the resource to be released.
- When a thread releases the resource, it calls
signal(orrelease), increasing the counter and unblocking waiting threads.
In iOS, the DispatchSemaphore class from GCD is often used to work with semaphores:
let semaphore = DispatchSemaphore(value: 1) // 1 means the resource is available to one thread
// In a thread:
semaphore.wait() // wait until the resource becomes available
// Work with the resource
semaphore.signal() // release the resource
Thus, semaphores help prevent race conditions and ensure correct access to shared resources.