Sobes.tech
Junior — Middle

How can the Semaphore mechanism be integrated into an existing program to manage resource access?

sobes.tech AI

Answer from AI

Semaphore is used to limit the number of threads that can access a certain resource simultaneously.

To integrate a semaphore into an existing iOS program (for example, in Swift), you need to:

  1. Create an instance of DispatchSemaphore with a maximum number of permits (for example, 1 for a mutex).
  2. Before accessing the resource, call wait() — if permits are exhausted, the thread will wait.
  3. After finishing with the resource, call signal() to release the permit.

Example:

let semaphore = DispatchSemaphore(value: 2) // maximum 2 concurrent accesses

func accessResource() {
    semaphore.wait() // wait for permit
    defer { semaphore.signal() } // ensure release

    // Work with the resource
    print("Accessing resource")
    Thread.sleep(forTimeInterval: 1) // simulate work
}

// Called from multiple threads
DispatchQueue.global().async { accessResource() }
DispatchQueue.global().async { accessResource() }
DispatchQueue.global().async { accessResource() }

This way, you can control concurrent access and avoid race conditions or resource overloads.

How can the Semaphore mechanism be integrated into an… - sobes.tech