【发布时间】: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