Junior — Middle
Mis erineb NSRecursiveLock tavalisest NSLockist mitmeprotsessilises kontekstis?
sobes.tech AI
Vastus AI-lt
NSLock is a simple mutual exclusion lock that prevents one thread from entering the critical section if another thread already holds the lock. If the thread that already holds the NSLock attempts to acquire it again, it will be blocked, leading to a deadlock.
NSRecursiveLock differs in that it allows the same thread to acquire the lock multiple times without blocking. This is useful when recursive methods call each other and use the same lock. NSRecursiveLock keeps a counter of acquisitions, and the lock is released only after the corresponding number of unlock calls.
Example:
let lock = NSRecursiveLock()
func recursiveFunction(_ count: Int) {
lock.lock()
defer { lock.unlock() }
if count > 0 {
recursiveFunction(count - 1) // recursive acquisition of the lock in the same thread
}
}
recursiveFunction(3)
If NSLock were used, a deadlock would occur during the recursive call.