GCD创建的线程数? [英] Number of threads created by GCD?

查看:96
本文介绍了GCD创建的线程数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于GCD创建的多少个线程,是否有很好的文献记载? 在WWDC,他们告诉我们它是围绕CPU内核建模的.但是,如果我举这个例子:

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

即使在iPad1上,它也会打开66个线程. (当本地调用Lion时,它还会打开66个线程).为什么是66?

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

推荐答案

首先,66 == 64(最大GCD线程池大小)+主线程+一些其他随机的非GCD线程.

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

第二,GCD不是魔术.它经过优化,可使CPU忙于大多数受CPU约束的代码. GCD的魔力"在于,当工作项无意间短暂地等待操作完成时,它动态地创建比CPU多的线程.

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.

话虽如此,代码可以通过故意休眠或等待事件而不是使用调度源来等待事件来混淆GCD调度程序.在这种情况下,工作块正在有效地实现其自己的调度程序,因此GCD必须假定已从线程池中选择了该线程.

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.

简而言之,如果您的代码更喜欢API之类的"sleep()",而您的代码更喜欢dispatch_after(),而不是手工制作的事件循环(Unix select()/poll(),Cocoa runloops或POSIX),则线程池将以最佳状态运行条件变量).

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

这篇关于GCD创建的线程数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆