Sobes.tech
Junior — Middle

Can you explain what types of locks exist and how they work in multithreaded programming?

sobes.tech AI

Answer from AI

In multithreaded programming, there are different types of locks that help synchronize access to shared resources:

  • Mutex — provides exclusive access to a resource. Only one thread can acquire the mutex at a time.
  • Recursive mutex — allows the same thread to acquire the lock multiple times without deadlock.
  • Read-Write Lock — allows multiple threads to read the resource simultaneously, but writing is only possible exclusively.
  • Semaphore — limits the number of threads that can access the resource simultaneously.
  • Spinlock — a thread checks the lock's availability in a loop without entering a waiting state.

Example of using a mutex in Swift:

let lock = NSLock()

func criticalSection() {
    lock.lock()
    // Critical section
    lock.unlock()
}

The choice of lock type depends on the task and performance and safety requirements.

Can you explain what types of locks exist and how… - sobes.tech