How to use NSLock safely in Swift

431 Views Asked by At

I'm new to Swift. I saw some NSLock examples online and they are all like below:

let lock = NSLock()

func test() {
    // some code
}

func run() {
    lock.lock()
    test()
    lock.unlock()
}

If the test function crashes, the lock will never be unlocked, so next call to the run function will be in dead lock. Is it true? if so, how to fix it?

1

There are 1 best solutions below

0
On

When used synchronously like in your example, the code is safe and well-defined.

If the program crashes, it's the job of the operating system to clean up the process and its memory. The lock will be removed from memory as well as the rest of your program after the crash under normal conditions (but this is up to the operating system and you don't need to care about it).