Search code examples
iosgrand-central-dispatch

Number of threads created by GCD?


Is there any good documention on how many threads are created by GCD? At WWDC, they told us it's modeled around CPU cores. However, if I call this example:

for (int i=1; i<30000; i++) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [NSThread sleepForTimeInterval:100000];
    });
}

it opens 66 threads, even on an iPad1. (It also opens 66 threads when called on Lion natively). Why 66?


Solution

  • First, 66 == 64 (the maximum GCD thread pool size) + the main thread + some other random non-GCD thread.

    Second, GCD is not magic. It is optimized for keeping the CPU busy with code that is mostly CPU bound. The "magic" of GCD is that it dynamically create more threads than CPUs when work items unintentionally and briefly wait for operations to complete.

    Having said that, code can confuse the GCD scheduler by intentionally sleeping or waiting for events instead of using dispatch sources to wait for events. In these scenarios, the block of work is effectively implementing its own scheduler and therefore GCD must assume that the thread has been co-opted from the thread pool.

    In short, the thread pool will operate optimally if your code prefers dispatch_after() over "sleep()" like APIs, and dispatch sources over handcrafted event loops (Unix select()/poll(), Cocoa runloops, or POSIX condition variables).