我尝试了 stackoverflow 上给出的多个解决方案/答案,但没有一个对我有用。其中一些如下:
https://stackoverflow.com/a/30495424/3145189
Is this safe to call wait() of DispatchSemaphore several times at one time?
https://stackoverflow.com/a/37155631/3145189
我正在尝试实现非常简单的事情,代码块或函数应该串行执行,而不管它是从哪个线程调用的。
我的示例代码:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
DispatchQueue.global().async {
self.testLog(name:"first")
}
DispatchQueue.global().async {
self.testLog(name:"second")
}
DispatchQueue.main.async {
self.testLog(name: "mainthread")
}
}
func testLog(name:String) -> Void {
for i in 1..<1000 {
print("thread test \(i) name =\(name)")
}
}
所以输出应该是这样的-
第一次线程调用
线程测试 1 name =first
线程测试 2 name =first
线程测试 3 name =first
.
.
.
线程测试 999 name =first
第二个线程调用
线程测试 1 name =second
线程测试 2 name =second
.
.
.
线程测试 999 name =second
主线程调用
线程测试1名称=mainthread
线程测试2名称=mainthread
.
.
.
线程测试999 名称=mainthread
如果在第一个线程上调用函数,它应该只为第一个线程继续打印日志。线程的顺序可能会有所不同我不在乎意味着即使它首先打印主线程日志然后是第二个和第一个无关紧要日志应该被分组。
最佳答案
这将串行执行调用。
保留对 serialQueue
的引用,您可以从任何线程提交 block 。
let serialQueue = DispatchQueue(label: "serial_queue")
serialQueue.async {
self.testLog(name: "first")
}
serialQueue.async {
self.testLog(name: "second")
}
serialQueue.async {
self.testLog(name: "third")
}
关于ios - 如何在swift中制作线程安全的代码块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51780904/