serial Dispatch Queue will use only one thread?

I find that serial queue will use more than one thread to run async code.

Here's the test code in 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)")
}


when I repeatedly execute the playground, there will be output like this sometimes. In my understanding, serial queue should use only one thread, but the log shows it used 2 threads. I am really confused on this.


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)}

Replies

A Dispatch serial queue guarantees that only one thread will being executing work on the queue at a time. It does not guarantee which specific thread will do that execution. Dispatch maintains a pool of worker threads and, when work becomes available to execute, it will allocate one thread from that pool to run that work.

One consequence of this is that it’s not safe to use thread-local storage in code run from a serial queue. If you have data you want to associate with the queue, you should use

setSpecific(key:value:)
and
getSpecific(key:)
.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Add a Comment