I'v read a lot how dispatch work. But i Still a little confusing about it.
For example, what if I have
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
}
}
}
}
}
And
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()
}
}
}
So what we have is that we have ViewController action. When we start action we dispatch to global queue and make Api request.
1 At that point (let it be point 1) does queue gathered thread for the queue ?
Then we make Api.request call which make another dispatch to global queue.
2 Does it queued to same queue as at point 1 ? or it queue to the another queue with the same QoS ? or CPU make decision by itself ? And does it create new Thread ? Actually I know that GCD make decision to create thread by itself but I don't make sense
Then Api calls completes and by some circumstances we dispatch to the main queue
Then we dispatch again to do "//Do other stuff here" and does it creates new queue ? or new Thread ?
Also I know that we have GCD thread pool limit by 64. Thats why I'm afraid of. Also I've seen wwdc talks about Thread explosion but doesn't understand so if we often dispatch from queue to queue does it danger to get thread explosion ?
I understand that create new Thread for queue is expensive, and that we do not need often dispatch from queue to queue because we waste time to dispatch.
But what about my example is it wrong dispatch like this ?