Sobes.tech
Middle

What is a semaphore?

sobes.tech AI

Answer from AI

A semaphore is a low-level synchronization primitive that controls access to resources. It maintains a counter (the number of available resources) and two main operations: wait and signal.

  • Wait: Decreases the counter. If the counter becomes negative (indicating no available resources), the current thread blocks until another thread signals.
  • Signal: Increases the counter. If the counter becomes non-negative and there are blocked threads, one of them is unblocked.

Semaphores can be used for:

  • Restrict access to a shared resource: Initialized with the maximum number of threads that can access simultaneously.
  • Task synchronization: One thread can wait until another thread completes a certain action.

In Darwin (the basis of iOS):

import Dispatch

// Creating a semaphore with a counter of 1 (similar to a mutex)
let semaphore = DispatchSemaphore(value: 1)

func accessResource() {
    // Wait for access (blocks if the counter is 0)
    semaphore.wait()

    // Access to the shared resource
    print("Access to resource granted")

    // Finish access (increments the counter)
    semaphore.signal()
    print("Access to resource finished")
}

// Example usage in a multithreaded environment
DispatchQueue.global().async {
    accessResource()
}

DispatchQueue.global().async {
    accessResource()
}

Main types of semaphores:

  • Binary semaphore: The counter value can only be 0 or 1. Acts similarly to a mutex.
  • Counting semaphore: The counter value can be greater than 1, allowing to limit access to the resource to a certain number of threads simultaneously.