Sobes.tech
Middle

What does synchronization do in the context of multithreading?

sobes.tech AI

Answer from AI

Synchronization in the context of multithreading prevents race conditions and ensures consistent access to shared resources (variables, files, network connections) from different threads.

Main synchronization mechanisms:

  • Mutex (mutual exclusion): Only one thread can own the mutex and access the protected resource.
  • Semaphore: Limits the number of threads that can access a resource simultaneously. Works with a counter.
  • Lock: A generalized concept often used to denote mutexes or other mechanisms that fully block access.
  • Dispatch Queue: In Grand Central Dispatch (GCD), queues can be serial or concurrent, providing synchronization by managing the order and number of tasks executing simultaneously. Serial queues guarantee task execution one by one, inherently ensuring synchronization for data accessed only from tasks of that queue.

Working principle: A thread wishing to access a shared resource first tries to acquire a lock. If the resource is free, the thread acquires the lock and works with the resource. After finishing, the thread releases the lock. If the resource is busy, other threads are blocked (wait) until the resource is freed.

Example of using a mutex to protect a critical section:

// Example in Objective-C using @synchronized
- (void)updateSharedResource {
    @synchronized (self) { // Lock on the self object
        // Critical section
        // Access to sharedResource is safe
        self.sharedResource++;
    } // Lock is automatically released when exiting the block
}
// Example in Swift using NSLock
let lock = NSLock()
var sharedCounter = 0

func incrementCounter() {
    lock.lock() // Attempt to acquire the lock
    // Critical section
    sharedCounter += 1
    lock.unlock() // Release the lock
}

Synchronization helps avoid issues such as:

  • Data corruption.
  • Deadlock of threads.
  • Livelock of threads.

Choosing the appropriate synchronization mechanism depends on the nature of the task and the type of resource.