Skip to content

Instantly share code, notes, and snippets.

@hfossli
Last active June 21, 2016 11:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hfossli/945b888cebc90802a4f05908ced8c9d8 to your computer and use it in GitHub Desktop.
Save hfossli/945b888cebc90802a4f05908ced8c9d8 to your computer and use it in GitHub Desktop.
#import <libkern/OSAtomic.h>
BOOL ale_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;
}
// *.h-file
@interface ALEQueue : NSObject
@property (nonatomic, strong, readonly) dispatch_queue_t queue;
- (instancetype)initWithQueue:(dispatch_queue_t)queue;
- (BOOL)isOnQueue;
@end
// *.m-file
#import <libkern/OSAtomic.h>
static int32_t _incrementer = 0;
@implementation ALEQueue {
int _queueKey;
CFNumberRef _value;
}
- (instancetype)initWithQueue:(dispatch_queue_t)queue
{
ALEAssert(queue);
self = [self init];
if(self)
{
_value = CFBridgingRetain(@(OSAtomicIncrement32(&_incrementer)));
_queue = queue;
dispatch_queue_set_specific(queue, &_queueKey, _value, nil);
}
return self;
}
- (BOOL)isOnQueue
{
CFStringRef value = dispatch_get_specific(&_queueKey);
if(value == _value)
{
return YES;
}
return NO;
}
- (void)dealloc
{
dispatch_queue_set_specific(_queue, &_queueKey, nil, nil);
CFRelease(_value);
}
@end
@hfossli
Copy link
Author

hfossli commented Jun 21, 2016

Is this code okay? My unit tests pass, but is there any pitfalls I'm not seeing? Any performance considerations to make?

@hfossli
Copy link
Author

hfossli commented Jun 21, 2016

Should I prefer Alternative 2 since I'm only calling dispatch_queue_set_specific(...) twice and not each time I ask isOnQueue?

@hfossli
Copy link
Author

hfossli commented Jun 21, 2016

Or should I prefer Alternative 1 due to its simplicity?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment