Junior — Middle
Can you explain the internal mechanism of NSLock in macOS or iOS?
sobes.tech AI
Answer from AI
NSLock is a class from Foundation that implements a mutual exclusion mechanism (mutex) for thread synchronization in iOS and macOS. Internally, NSLock uses system primitives such as pthread_mutex to ensure exclusive access to a resource.
When a thread calls lock(), NSLock attempts to acquire the mutex. If the mutex is already held by another thread, the calling thread is blocked and waits until the mutex is released. The unlock() method releases the mutex, allowing other threads to continue.
Example usage:
let lock = NSLock()
func criticalSection() {
lock.lock()
// Critical section: work with shared resources
lock.unlock()
}
Thus, NSLock provides a simple and efficient locking mechanism to prevent data races between threads.