如何在Swift中安全使用NSLOCK
我是Swift的新手。我在网上看到了一些NSLOCK示例,它们都喜欢以下:
let lock = NSLock()
func test() {
// some code
}
func run() {
lock.lock()
test()
lock.unlock()
}
如果测试功能崩溃,锁将永远不会被解锁,因此下一个呼叫运行函数将处于死锁中。是真的吗?如果是这样,如何修复它?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您的示例中同步使用时,代码是安全且定义明确的。
如果程序崩溃,则是操作系统清理过程及其内存的工作。
在正常情况下崩溃后,将从内存以及程序的其余部分中删除锁(但这取决于操作系统,您不需要关心它)。
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).
是的,如果您的test()函数要引发错误,并且您的Run()函数没有捕获它,则可以将NSLOCK留在锁定状态。
这是一种避免这种情况的简单方法:
即使控制函数是由于抛出的错误,延期块中的代码即使是在控制函数时运行的。
Yes, if your test() function were to throw an error, and your run() function didn't catch it, you could leave the NSLock in a locked state.
Here's a simple way to avoid that:
Code in a defer block is run when control leaves the function, even if it's due to a thrown error.