Junior — Middle
Kas saaksite selgitada semafori tööpõhimõtet mitmetöötlusprogrammeerimises?
sobes.tech AI
Vastus AI-lt
A semaphore is a synchronization mechanism in multithreaded programming that controls access to a shared resource. It contains a counter that indicates how many threads can access the resource simultaneously.
Working principle:
- Initially, the semaphore's counter is set to the number of available resources.
- When a thread wants to access, it calls the "wait" (or "acquire") operation, which decreases the counter by 1.
- If the counter becomes less than zero, the thread is blocked and waits until another thread releases the resource.
- When a thread releases the resource, it calls the "signal" (or "release") operation, which increases the counter by 1 and unblocks waiting threads.
Example in Swift using DispatchSemaphore:
let semaphore = DispatchSemaphore(value: 2) // allows 2 threads to run concurrently
DispatchQueue.global().async {
semaphore.wait() // attempt to access
print("Thread has started working")
sleep(2) // simulate work
print("Thread has finished working")
semaphore.signal() // release resource
}
This way, the semaphore helps limit the number of threads working simultaneously with a shared resource, preventing race conditions and ensuring data integrity.