首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DispatchQueue.sync {}阻塞“线程”或“队列”

DispatchQueue.sync {}阻塞“线程”或“队列”
EN

Stack Overflow用户
提问于 2022-05-17 09:04:37
回答 1查看 466关注 0票数 0

我很困惑。

下面的代码肯定会导致死锁:

代码语言:javascript
复制
// Will execute
DispatchQueue.main.async { // Block 1 
  // Will execute
    DispatchQueue.main.sync { // Block 2
     // Will not be executed
    }
    // Will not be executed
}

因为

在主队列上question

  • Because
  1. 之后,它向主队列提交第一个块以在某一时刻执行
  2. ,系统决定运行block1
  3. .sync方法块“线程/队列?”<- My
  4. --“线程/队列”被阻塞,块2不能在块1完成之前执行,因为主队列是串行队列,它连续执行任务,在另一个完成

之前不能执行。

我的问题是:sync是阻止current thread it's executing on还是current queue?(我理解线程和队列之间的区别)

互联网上的大多数答案都说它阻塞了线程。

  1. If块线程->为什么sync { }块仍然可以执行,因为线程被阻塞了?

如果阻塞队列

  1. ->更有意义?由于队列被阻塞,我们无法在其他人完成

之前执行其中一个

我发现了一些关于这个的讨论:

dispatch_sync inside dispatch_sync causes deadlock

Difference Between DispatchQueue.sync vs DispatchQueue.async

What happens if dispatch on same queue?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-17 16:39:35

你问:

我的问题是:同步是阻止它正在执行的当前线程还是当前队列?

它阻塞当前线程。

在处理串行队列(如主队列)时,如果该队列运行的线程被阻塞,则在队列再次空闲之前阻止该队列上的任何其他内容运行。串行队列一次只能使用一个线程。因此,从任何串行队列同步分配到自身将导致死锁。

但是,sync在技术上不会阻塞队列。它阻塞当前线程。特别要注意的是,当处理并发队列(例如全局队列或自定义并发队列)时,该队列可以同时使用多个工作线程。因此,仅仅因为一个工作线程被阻塞,它就不会阻止并发队列在另一个未阻塞的工作线程上运行另一个分派的项。因此,从并发队列同步分配到自身通常不会导致死锁(只要您不耗尽非常有限的工作线程池)。

例如。

代码语言:javascript
复制
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
}

你问:

  1. If块线程->为什么sync { }块仍然可以执行,因为线程被阻塞了?

正如您在自己的代码片段中指出的那样,sync块不执行(在串行队列场景中)。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72271150

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档