Number of threads created by GCD?

后端 未结 3 1441
[愿得一人]
[愿得一人] 2020-12-07 23:26

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:

<
相关标签:
3条回答
  • 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).

    0 讨论(0)
  • 2020-12-07 23:33

    Number of busy threads is equal to CPU cores. Blocked threads (you block them with sleepForTimeInterval) are not counted.

    If you change your code to this (Swift):

    for _ in 1..<30000 {
        DispatchQueue.global().async {
            while true {}
         }
    }
    

    you'll see that there are just 2 threads created (on iPhone SE):

    There is a thread limit so that your app is not killed because of big memory consumption if you have problem with blocked threads (usually because of deadlock).

    Never block threads and you'll have them as much as your cores.

    0 讨论(0)
  • 2020-12-07 23:51

    The documentation avoids mentioning the number of threads created. Mostly because the optimal number of threads depends heavily on the context.

    One issue with Grand Cendral Dispatch is that it will spawn a new thread if a running task blocks. That is, you should avoid blocking when using GCD as having more threads than cores is suboptimal.

    In your case, GCD detects that the task is inactive, and spawns a new thread for the next task.

    Why 66 is the limit is beyond me.

    0 讨论(0)
提交回复
热议问题