Sleep in DispatchQueue?

I guess the answer is "This is not a reasonable pattern for Dispatch"?

Correct. ahti explains this but I want to go into a little more detail.

Dispatch is responsible for mapping work on queues to worker threads. The goal is to have one thread put core. However, if a thread blocks then Dispatch may need to spawn extra worker threads to pick up the slack while the thread is blocked. Dispatch has a bunch of logic to handle this but in the worst case scenario you can experience a thread explosion.

If you want more info on this, watch WWDC 2015 Session 718 Building Responsive and Efficient Apps with GCD. If you want an outline of current Dispatch best practices, watch WWDC 2017 Session 706 Modernizing Grand Central Dispatch Usage.

In your case the best option would be to use the Thread API, so that your thread does not tie up a Dispatch worker thread. That API is part of Swift’s Foundation because it’s still useful. And with the block syntax introduced in the 2016 OS releases, it’s no harder to use than Dispatch.

Thread {
    while true {
        guard let task = GET_PENDING_TASK() else {
            SLEEP(interval)
            continue
        }
        PROCESS(task)
    }
}

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple

3 Likes