我已经阅读了很多调度如何工作。但我还是有点困惑。
例如,如果我有
class ViewController: UIViewController {
@IBAction func actionDoStuff(_ sender: UIButton) {
DispatchQueue.global(qos: .userInitiated).async {
Api.request { result in
//completes in main thread
//what if I need to dispatch again ?
DispatchQueue.global(qos: .userInitiated).async {
//Do other stuff here
}
}
}
}
}
和
class Api {
static func request(completion: @escaping (Result<String, NSError>) -> Void) {
DispatchQueue.global(qos: .userInitiated).async {
//url session configure
let url = URL(fileURLWithPath: "test.com")
URLSession.shared.dataTask(with: url) { data, response, error in
DispatchQueue.main.async {
completion(.success("Request are success")) //without error handler for simplifier
}
}.resume()
}
}
}
所以我们所拥有的是我们有 ViewController 动作。当我们开始行动时,我们分派到全局队列并发出 Api 请求。
1 那时(让它成为第 1 点)队列是否为队列收集线程?
然后我们进行 Api.request 调用,该调用对全局队列进行另一个调度。
2 它是否与点 1 排队到同一队列?或者它排队到另一个具有相同 QoS 的队列?还是 CPU 自己做决定?它会创建新的 Thread 吗?实际上我知道 GCD 自己决定创建线程,但我没有意义
然后 Api 调用完成,在某些情况下我们分派到主队列
然后我们再次派发做“//在这里做其他事情”,它会创建新的队列吗?还是新线程?
另外我知道我们的 GCD 线程池限制为 64。这就是我害怕的原因。我还看到 wwdc 谈论线程爆炸,但不明白,所以如果我们经常从队列分派到队列,线程爆炸是否危险?
我知道为队列创建新线程很昂贵,而且我们不需要经常从队列到队列进行调度,因为我们浪费时间进行调度。
但是我的例子是这样的错误调度吗?