Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With dispatch_async, use your own individual queues or your own global queue?

So when using dispatch_async ...

Say you're making a network connection for example...

dispatch_queue_t otherQ = dispatch_queue_create(NULL, 0);

__weak MyClass *myself = self;
dispatch_async(otherQ,
    ^{
     myself.searchResultsRA = [myself dataFrom:happyUrl ifError:nil];
    dispatch_async(dispatch_get_main_queue(), ^{ if (after) after(); });
    });

dispatch_release(otherQ);

Notice I am creating a queue "right there" for that call.

So, every call like that in the app, simply creates its own queue "there and then" to use.

Alternately, you can just create one queue as a global for your app, and keep it around, and always use that one same queue. (I guess, you'd really "never release it" it would just persist for the life of the app.)

(Note - I am not talking about Apple's "global queue" ..dispatch_get_global_queue .. nothing to do with that .. I simply mean you can create your own one queue and always use that same queue.)

I've never really understood if one approach is preferred or if there are dangers associated with either, or any other issues.

In short, which approach to use?

like image 338
Fattie Avatar asked Jan 31 '26 06:01

Fattie


2 Answers

These alternatives accomplish very different things. If you create a new queue each time, then all of them can run at once. If you always use the same (serial; doesn't apply to concurrent ones) queue, the blocks on it will run one at a time in order.

You would typically use the latter in either of two situations:

  • To protect something that's not threadsafe from being used from more than one thread at once (most common use of serial queues)

  • To intentionally reduce the amount of concurrency in your app to conserve resources (whether that be memory, or server connections, or what).

like image 76
Catfish_Man Avatar answered Feb 02 '26 18:02

Catfish_Man


In addition to the answer from @Catfish_Man, consider that you currently have no control over how many downloads you're running concurrently and that you have no ability to cancel the downloads if the user changes their mind. Do you really want to make the user wait for one thing before requesting another, or risk flooding the network with requests and having them all fail?

In general, should you really be using GCD, or should you really opt for the higher level NSOperationQueue APIs.

Ising GCD directly, while it may offer the 'minimum code to write', does come with drawbacks/compromises and you should make yourself aware of them before using that approach.

like image 37
Wain Avatar answered Feb 02 '26 18:02

Wain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!