dispatch_queue_t need to be released using dispatch_release()?

14,241

Solution 1

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.

Solution 2

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.

Share:
14,241
Nic Hubbard
Author by

Nic Hubbard

Updated on July 28, 2022

Comments

  • Nic Hubbard
    Nic Hubbard over 1 year

    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?

  • Nic Hubbard
    Nic Hubbard about 12 years
    Ok, but if I do it outside the queue, won't it get released automatically?
  • Nic Hubbard
    Nic Hubbard about 12 years
    Ok, so I just need to release it outside of the dispatch_asynch call?
  • jkh
    jkh about 12 years
    Yes. Specifically, you need to do it in the same scope as the create call lest you set a land-mine for yourself that you later step on, as I illustrated in my answer (the only exception to this rule might be finalizers, but let's not confuse things :) )
  • Pochi
    Pochi over 11 years
    @NicHubbard It will get released when all the queue's work is done, for instance you could create a queue, dispatch 3 - 4 blocks to it, and release it after the dispatch calls. The queue will remain retained until all the blocks have finished their corresponding tasks. At this point you no longer need this queue.