我很困惑。
下面的代码肯定会导致死锁:
// Will execute
DispatchQueue.main.async { // Block 1
// Will execute
DispatchQueue.main.sync { // Block 2
// Will not be executed
}
// Will not be executed
}因为
在主队列上question
.sync方法块“线程/队列?”<- My 之前不能执行。
我的问题是:sync是阻止current thread it's executing on还是current queue?(我理解线程和队列之间的区别)
互联网上的大多数答案都说它阻塞了线程。
sync { }块仍然可以执行,因为线程被阻塞了?如果阻塞队列
之前执行其中一个
我发现了一些关于这个的讨论:
dispatch_sync inside dispatch_sync causes deadlock
Difference Between DispatchQueue.sync vs DispatchQueue.async
发布于 2022-05-17 16:39:35
你问:
我的问题是:同步是阻止它正在执行的当前线程还是当前队列?
它阻塞当前线程。
在处理串行队列(如主队列)时,如果该队列运行的线程被阻塞,则在队列再次空闲之前阻止该队列上的任何其他内容运行。串行队列一次只能使用一个线程。因此,从任何串行队列同步分配到自身将导致死锁。
但是,sync在技术上不会阻塞队列。它阻塞当前线程。特别要注意的是,当处理并发队列(例如全局队列或自定义并发队列)时,该队列可以同时使用多个工作线程。因此,仅仅因为一个工作线程被阻塞,它就不会阻止并发队列在另一个未阻塞的工作线程上运行另一个分派的项。因此,从并发队列同步分配到自身通常不会导致死锁(只要您不耗尽非常有限的工作线程池)。
例如。
let serialQueue = DispatchQueue(label: "serial")
serialQueue.async {
serialQueue.sync {
// will never get here; deadlock
print("never get here")
}
// will never get here either, because of the above deadlock
}
let concurrentQueue = DispatchQueue(label: "concurrent", attributes: .concurrent)
concurrentQueue.async {
concurrentQueue.sync {
// will get here as long as you don't exhaust the 64 worker threads in the relevant QoS thread pool
print("ok")
}
// will get here
}你问:
sync { }块仍然可以执行,因为线程被阻塞了?正如您在自己的代码片段中指出的那样,sync块不执行(在串行队列场景中)。
https://stackoverflow.com/questions/72271150
复制相似问题