小编sim*_*zan的帖子

串行调度队列将仅使用一个线程?

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

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)

macos multithreading ios swift dispatch-queue

4
推荐指数
1
解决办法
2211
查看次数

标签 统计

dispatch-queue ×1

ios ×1

macos ×1

multithreading ×1

swift ×1