Are Objective-C blocks always executed in a separate thread?

Are Objective-C locks always executed in a separate thread?

In particular, I am asking about the sendAsynchronousRequest: queue: completHandler method of the NSURLConnection class. This is the scenario:

The main thread (1st thread) calls the sendAsynchronousRequest method. sendAsynchronousRequest is executed in the second thread controlled by NSOperationQueue when the method is completed and calls the commpletionHandler, which thread is running? 2nd stream? yet another third thread? or 1st stream?

Thanks!

+7
source share
4 answers

It executes it in any operation queue that you specify as a queue argument:

Loads data to request a URL and executes a handler block in the work queue when the request completes or fails.

The queue parameter is documented as:

The operational queue to which the handler block is sent when the request completes or fails.

So, really, before NSOperationQueue exactly how many threads are used. I would expect a behavior pool - so when there can be multiple threads, I would not expect each thread to be handled differently.

+6
source

A block is just a closure, for example, you have it in python or in functional languages. They do not "run along the stream"; they run where they are called.

 int main(void) { void (^f)(void) { printf("hello world!\n"); } f(); return 0; } 

Does what you think it does, there are no send queues, no threads, nothing.

Although, when you have blocks with all their good capture semantics, it is very tempting to have APIs to plan their execution everywhere. But basically a block is the same as a function pointer, and an ad-hoc structure containing the entire captured variable passed as an argument to the callback (it is even implemented in the compiler).

+6
source

Blocks are executed wherever they are told. The packaging code in the block does not affect the thread or the queue in which it will be launched. In your specific case, as described, the completion block is executed in the queue, which is passed in the queue parameter.

I'm not sure, for your purposes, if you really need to distinguish between a queue and a thread, the key principle is that the URL request is executed asynchronously with the calling code, and the completion block is executed on the queue as a method parameter.

+3
source

As others have said, it will work in any queue specified by you. If this is a background queue and you want to execute some code in the main thread, you can block the GCD block by accessing the main queue. Your completion block will look something like this:

 ^(NSURLResponse *response, NSData *data, NSError*error){ // do whatever in the background dispatch_async(dispatch_get_main_queue(), ^{ // this block will run on the main thread }); } 
+3
source

All Articles