Brad Larson Brad Larson - 1 year ago 139
iOS Question

How can I verify that I am running on a given GCD queue without using dispatch_get_current_queue()?

Recently, I had the need for a function that I could use to guarantee synchronous execution of a given block on a particular serial dispatch queue. There was the possibility that this shared function could be called from something already running on that queue, so I needed to check for this case in order to prevent a deadlock from a synchronous dispatch to the same queue.

I used code like the following to do this:

void runSynchronouslyOnVideoProcessingQueue(void (^block)(void))
dispatch_queue_t videoProcessingQueue = [GPUImageOpenGLESContext sharedOpenGLESQueue];

if (dispatch_get_current_queue() == videoProcessingQueue)
dispatch_sync(videoProcessingQueue, block);

This function relies on the use of
to determine the identity of the queue this function is running on and compares that against the target queue. If there's a match, it knows to just run the block inline without the dispatch to that queue, because the function is already running on it.

I've heard conflicting things about whether or not it was proper to use
to do comparisons like this, and I see this wording in the headers:

Recommended for debugging and logging purposes only:

The code must not make any assumptions about the queue returned,
unless it is one of the global queues or a queue the code has itself
created. The code must not assume that synchronous execution onto a
queue is safe from deadlock if that queue is not the one returned by

Additionally, in iOS 6.0 (but not yet for Mountain Lion), the GCD headers now mark this function as being deprecated.

It sounds like I should not be using this function in this manner, but I'm not sure what I should use in its place. For a function like the above that targeted the main queue, I could use
[NSThread isMainThread]
, but how can I check if I'm running on one of my custom serial queues so that I can prevent a deadlock?

Answer Source

Assign whatever identifier you want using dispatch_queue_set_specific(). You can then check your identifier using dispatch_get_specific().

Remember that dispatch_get_specific() is nice because it'll start at the current queue, and then walk up the target queues if the key isn't set on the current one. This usually doesn't matter, but can be useful in some cases.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download