2

I understand that GCD will only create as many threads as needed to make best use of the CPU. In code using dispatch_async to launch about 30 background tasks, I'm seeing the number of threads jump by about 30 in Activity Monitor. I would not have expected that, since it's only a dual core PC.

I'm sure I'm misunderstanding something. Can someone tell me what is going on?

Nick Moore
  • 15,547
  • 6
  • 61
  • 83
  • 1
    Do your dispatched blocks, erm, block? I.e., do they do filesystem/networking I/O? –  Jan 27 '11 at 21:25

1 Answers1

5

One situation where GCD will increase the thread pool by adding more threads is I/O contention. If a dispatched block waits for filesystem or networking I/O, it doesn’t use the CPU, hence GCD thinks the CPU is idle and able to process more threads.

In fact, depending on the nature of the dispatched blocks, this can increase I/O contention further and reach the limit of 512 worker threads. Mike Ash has written a blog post about this situation.

  • Ah, interesting. The threads are calling `AXUIElememt...` functions to inspect other applications, which does seem to require the cooperation of the app in question (though I've never quite got to the bottom of how it works). This could be behind the reason for the blocking. – Nick Moore Jan 27 '11 at 21:43
  • 1
    To elaborate, dispatch has no mechanism to distinguish between a thread that's blocked waiting for a resource to be freed up by another thread and a thread that's blocked waiting for some unrelated resource. Not creating a new thread would risk deadlock as the "provider" task gets blocked behind the "consumer" task. If you use dispatch itself to block (via dispatch sync, dispatch semaphores, etc...) I believe libdispatch will make a 'continuation' for your thread and reuse the thread itself (presumably by saving off its stack and such). – Catfish_Man Jan 27 '11 at 21:47
  • 1
    Further update. Based on what you've said, I've realised that each of my tasks does a `dispatch_sync(dispatch_get_main_queue(),...` call, which will of course block most of the time. I took out that and the number of threads created dropped dramatically. – Nick Moore Jan 27 '11 at 21:51