【问题标题】:serial Dispatch Queue will use only one thread?串行调度队列将只使用一个线程?
【发布时间】:2018-12-06 00:49:17
【问题描述】:

我发现串行队列将使用多个线程来运行异步代码。 这是 Playground 中的测试代码。

import Foundation  

let q = DispatchQueue(label: "test")  
q.async {  
    print("hi \(Thread.current)")  
}  
q.async {  
    print("hi \(Thread.current)")  
}  
q.async {  
    print("hi \(Thread.current)")  
}  
q.async {  
    print("hi \(Thread.current)")  
}  
q.async {  
    print("hi \(Thread.current)")  
}  

当我反复执行操场时,有时会出现这样的输出。据我了解,串行队列应该只使用一个线程,但日志显示它使用了 2 个线程。我真的很困惑。正确的行为是什么?

hi <NSThread: 0x7fc26a467b90>{number = 2, name = (null)}  
hi <NSThread: 0x7fc26a467b90>{number = 2, name = (null)}  
hi <NSThread: 0x7fc26a467b90>{number = 2, name = (null)}  
hi <NSThread: 0x7fc26a467b90>{number = 2, name = (null)}  
hi <NSThread: 0x7fc26b1003e0>{number = 3, name = (null)} 

【问题讨论】:

  • 总的来说,你想达到什么目的?
  • 一般来说队列和线程是没有关系的;例外是主队列。在主队列上调度的任务保证在主线程上运行。在任何其他队列上分派的任务可以在任何可用线程上运行。串行调度队列确保一次只运行一个提交到队列的任务,但不保证线程。

标签: ios swift multithreading macos dispatch-queue


【解决方案1】:

您说得对,串行队列在“a”时间只会使用 1 个线程。

但是同一个线程(NSThread 对象)是否会执行每个排入队列的代码块?没有。

为了更清楚地说明第一个陈述,我将重新表述它..

串行队列每次执行块时一次只使用 1 个线程。这意味着两个线程永远不会在任何时间点对任何代码块进行操作。

不能保证哪个线程执行从队列中入队/出队的 FIFO 顺序的代码。但可以保证的是,任何“一个”任意工作线程都会执行该操作。

据我所知,在内部,每个块的线程分配都是自动的。 “只有一个线程”并不意味着“总是同一个线程”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多