Last active
June 21, 2016 11:27
-
-
Save hfossli/945b888cebc90802a4f05908ced8c9d8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// *.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 |
Should I prefer Alternative 2 since I'm only calling dispatch_queue_set_specific(...)
twice and not each time I ask isOnQueue
?
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
Is this code okay? My unit tests pass, but is there any pitfalls I'm not seeing? Any performance considerations to make?