Sobes.tech
Middle

Mis vahe on semafori ja mutex vahel

sobes.tech AI

Vastus AI-lt

Semaphore is a general synchronization mechanism used to control access to a limited resource among multiple competing threads. It maintains an integer value that decreases when a resource is acquired and increases when it is released. If the semaphore value is zero, an attempt to acquire it blocks the thread until another thread releases the resource. It can be used to limit the number of threads running simultaneously.

A mutex (mutual exclusion) is a binary semaphore that can be either locked or unlocked. It is used to protect a critical section of code from concurrent access by multiple threads. Only one thread can acquire the mutex at a time. The thread that has acquired the mutex cannot be interrupted by another thread trying to acquire the same mutex. If an attempt is made to acquire a locked mutex, the thread will be blocked until it is released.

Key differences:

Characteristic Semaphore Mutex
Type General synchronization mechanism Binary semaphore (special case of semaphore)
Value Integer (>= 0) Binary (0 or 1)
Purpose Managing access to resources, limiting Protecting critical sections, mutual exclusion
Owner May not have an owner Always has an owner (the thread that acquired it)
Usage in iOS DispatchSemaphore Often implemented via DispatchQueue.sync or NSRecursiveLock

Example of using a mutex to protect a critical section:

// In the context of GCD (Grand Central Dispatch)
let serialQueue = DispatchQueue(label: "com.example.criticalSection")

serialQueue.sync {
    // Critical section code
    // Only one thread can be here at any time
}

Example of using a semaphore to limit parallel tasks:

// In the context of GCD (Grand Central Dispatch)
let semaphore = DispatchSemaphore(value: 3) // Allow 3 parallel tasks

DispatchQueue.global().async {
    semaphore.wait() // Decreases semaphore value by 1. Blocks if the value is 0.

    // Code of the task executed in parallel
    print("Task is running")

    Thread.sleep(forTimeInterval: 1) // Simulate work

    semaphore.signal() // Increases semaphore value by 1. Releases waiting thread if any.
    print("Task completed")
}

// You can start several such blocks. Only 3 will run simultaneously.