0

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?

Bruce L
  • 41
  • 2
  • 2
    If `test` crashes, wouldn't the whole program terminate? Are you talking about some other kind of "crash"? Also, why are you using primitives such as `NSLock` in the first place? What are you trying to do, that can't be done with GCD and/or the Swift Concurrency? – Sweeper Apr 19 '22 at 18:40

1 Answers1

0

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).

Bradley Mackey
  • 6,777
  • 5
  • 31
  • 45