Sobes.tech
Junior — Middle

Can you explain what a semaphore is in the context of programming and thread synchronization?

sobes.tech AI

Answer from AI

A semaphore is a synchronization mechanism used to control access of multiple threads to a shared resource.

It contains a counter that indicates how many threads can access the resource simultaneously. When a thread wants to enter a critical section, it attempts to "acquire" the semaphore:

  • If the counter is greater than zero, it is decremented by one, and the thread continues.
  • If the counter is zero, the thread is blocked and waits until another thread releases the semaphore.

When a thread finishes working with the resource, it releases the semaphore by increasing the counter, allowing other threads to proceed.

Example of using a semaphore in Swift (iOS):

let semaphore = DispatchSemaphore(value: 2) // allow 2 threads simultaneously

DispatchQueue.global().async {
    semaphore.wait() // attempt to acquire the semaphore
    print("Thread started working")
    sleep(2) // simulate work
    print("Thread finished working")
    semaphore.signal() // release the semaphore
}

Thus, a semaphore helps control the number of threads working simultaneously with a shared resource, preventing race conditions and ensuring correct operation.

Can you explain what a semaphore is in the context of… - sobes.tech