sim*_*zan 4 macos multithreading ios swift dispatch-queue
我发现串行队列将使用多个线程来运行异步代码。这是操场上的测试代码。
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)")
}
Run Code Online (Sandbox Code Playgroud)
当我重复执行playground时,有时会出现这样的输出。根据我的理解,串行队列应该只使用一个线程,但日志显示它使用了 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)}
Run Code Online (Sandbox Code Playgroud)
您说得对,串行队列在“a”时间仅使用 1 个线程。
但是同一个线程(NSThread 对象)会执行排队到队列中的每个代码块吗?不。
为了使第一个陈述更加清晰,我将重新措辞。
串行队列每个块执行一次仅使用 1 个线程。这意味着两个线程永远不会在任何时间点对任何代码块执行操作。
无法保证哪个线程执行从队列中入队/出队的 FIFO 顺序的代码。但可以保证的是任何“一个”任意工作线程都将执行该操作。
据我所知,在内部,对于每个块,线程分配是自动的。“仅一个线程”并不意味着“始终使用同一线程”。
| 归档时间: |
|
| 查看次数: |
2211 次 |
| 最近记录: |