Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dispatch_queue_t need to be released using dispatch_release()?

I have two GCD blocks that are async. The first is for the background thread, the second runs on the main thread. This works great, but I just saw somewhere talking that I might need to release them using dispatch_release(). E.g.:

// Use gcd
dispatch_queue_t queue = dispatch_queue_create("com.awesome", 0);
dispatch_queue_t main = dispatch_get_main_queue();

//  do the long running work in bg async queue
// within that, call to update UI on main thread.
dispatch_async(queue, ^{ 
   // Do work in the background



    // Release
    dispatch_release(queue);

   dispatch_async(main, ^{ 

       // Main


       // Release
       dispatch_release(main);

   });//end
});//end

Is this true? Do I need to release them here?

like image 335
Nic Hubbard Avatar asked Feb 23 '12 23:02

Nic Hubbard


2 Answers

You only need to release the queue created with dispatch_queue_create. The main queue will always exist, and it doesn't make sense to release it.

Any blocks added to the queue will retain the queue itself, so you can safely call dispatch_release(queue) after your dispatch_async call. Best to do this outside the block after the code you've written here.

like image 94
rsez Avatar answered Sep 29 '22 20:09

rsez


Only release queues that you create; don't release the main queue or the global concurrent queues (or, again, any you did not create yourself). It's also not a good idea to nest the release within the work block enqueued on that queue, as you're doing, because that's doing it in the wrong scope and this:

queue = dispatch_queue_create(...)
dispatch_async(queue, ^{ something; dispatch_release(queue); });
dispatch_async(queue, ^{ something else}); // CRASH!

Won't work when you later change the code to add that 2nd dispatch_async(). Always pairing your create/release calls in the same scope, assuming that you can, is a better stylistic choice.

like image 45
jkh Avatar answered Sep 29 '22 19:09

jkh