Are Objective-C blocks always executed in a separate thread?
Specifically, I'm asking about the sendAsynchronousRequest:queue:completionHandler method of the NSURLConnection class. This is the scenario:
Main thread (1st thread) calls the sendAsynchronousRequest method the sendAsynchronousRequest is executed on a 2nd thread, managed by the NSOperationQueue when method is completed and calls commpletionHandler, which thread is it executed on? 2nd thread? yet another 3rd thread? or the 1st thread?
Thanks!
It executes it on whatever operation queue you specify as the queue
argument:
Loads the data for a URL request and executes a handler block on an operation queue when the request completes or fails.
The queue
parameter is documented as:
The operation queue to which the handler block is dispatched when the request completes or failed.
So it's really up to the NSOperationQueue
exactly how many threads are used. I'd expect pooling behaviour - so while there can be multiple threads, I wouldn't expect a different thread per handler, necessarily.
A block is just a closure, like you have them in python or functional languages. They don't "run on a thread" they run where they are called.
int main(void)
{
void (^f)(void) { printf("hello world!\n"); }
f();
return 0;
}
Does just what you think it does, no dispatch queues, no threads, no nothing.
Though, once you have blocks with all their nice capture semantics, it's very tempting to have APIs to schedule their execution everywhere. But basically, a block, is just the same as a function pointer and an ad-hoc struct containing all the variable captured, passed as an argument to the callback (it's even how it's implemented in the compiler).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With