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

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


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.


This is a very simple solution. It is not as performant as using dispatch_queue_set_specific and dispatch_get_specific manually – I don't have the metrics on that.

#import <libkern/OSAtomic.h>BOOL dispatch_is_on_queue(dispatch_queue_t queue){    int key;    static int32_t incrementer;    CFNumberRef value = CFBridgingRetain(@(OSAtomicIncrement32(&incrementer)));    dispatch_queue_set_specific(queue, &key, value, nil);    BOOL result = dispatch_get_specific(&key) == value;    dispatch_queue_set_specific(queue, &key, nil, nil);    CFRelease(value);    return result;}