Sobes.tech
Middle

What tools can you use to solve thread synchronization problems?

sobes.tech AI

Answer from AI

  • DispatchGroup: For waiting for a group of asynchronous tasks to complete.
  • DispatchSemaphore: To limit the number of threads accessing a resource simultaneously.
  • NSRecursiveLock: Allows a thread to acquire the lock multiple times without causing a deadlock.
  • NSConditionLock: A lock that can only be acquired when a certain condition is true.
  • OSAtomic functions: Low-level atomic operations for simple cases (deprecated, prefer using atomic properties in Swift or C++ std::atomic).
  • @synchronized: An Objective-C directive for creating a critical section.
// Example of using DispatchSemaphore to limit access to a resource
import Dispatch

let semaphore = DispatchSemaphore(value: 2) // Allow only 2 threads at a time

DispatchQueue.global().async {
    semaphore.wait() // Decrement the counter, block if 0
    print("Thread 1 is working")
    sleep(1)
    print("Thread 1 finished")
    semaphore.signal() // Increment the counter
}

DispatchQueue.global().async {
    semaphore.wait()
    print("Thread 2 is working")
    sleep(1)
    print("Thread 2 finished")
    semaphore.signal()
}

DispatchQueue.global().async {
    semaphore.wait()
    print("Thread 3 is working")
    sleep(1)
    print("Thread 3 finished")
    semaphore.signal()
}
What tools can you use to solve thread… - sobes.tech