Sobes.tech
Junior — Middle

Have you used semaphore mechanisms in your projects to manage resource contention?

sobes.tech AI

Answer from AI

Yes, the semaphore mechanism is often used to control access to limited resources in multithreaded applications. In iOS, for example, you can use DispatchSemaphore to limit the number of tasks running simultaneously.

Example of using DispatchSemaphore:

let semaphore = DispatchSemaphore(value: 2) // allow 2 tasks at the same time

DispatchQueue.global().async {
    semaphore.wait() // decrement the counter, wait if 0
    // critical section
    print("Task started")
    sleep(2) // simulate work
    print("Task finished")
    semaphore.signal() // increment the counter
}

This approach helps prevent data races and control concurrency when working with limited resources, such as database access or network requests.

Have you used semaphore mechanisms in your projects… - sobes.tech