Sobes.tech
Junior — Middle

Kas saaksite selgitada, mis on semafor programmeerimise ja lõimede sünkroniseerimise kontekstis?

sobes.tech AI

Vastus AI-lt

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 the critical section, it tries 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 continue.

Example of using a semaphore in Swift (iOS):

let semaphore = DispatchSemaphore(value: 2) // allows 2 threads at the same time

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

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