如何给变量加锁,防止不同线程同时修改,导致错误?
我试过用
func lock(obj: AnyObject, blk:() -> ()) {
objc_sync_enter(obj)
blk()
objc_sync_exit(obj)
}
但我仍然有多线程问题。
最佳答案
共享值(value)
如果你有一个共享值,你想像这样以线程安全的方式访问
var list:[Int] = []
调度队列
您可以创建自己的串行 DispatchQueue
。
let serialQueue = DispatchQueue(label: "SerialQueue")
调度同步
现在不同的线程可以安全地访问list
,您只需要将代码写入一个闭包中并分发给您的串行队列。
serialQueue.sync {
// update list <---
}
// This line will always run AFTER the closure on the previous line 👆👆👆
由于串行队列一次执行一个闭包,因此对list
的访问将是安全的。
Please note that the previous code will block the current thread until the closure is executed.
调度异步
如果不想阻塞当前线程直到串行队列处理完闭包,可以异步调度闭包
serialQueue.async {
// update list <---
}
// This line can run BEFORE the closure on the previous line 👆👆👆
关于swift - 使用 GCD 在 Swift 3 中安全地锁定变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45653331/