Skip to content

Instantly share code, notes, and snippets.

@ridiculousfish
Created June 26, 2012 09:22
Show Gist options
  • Save ridiculousfish/2994621 to your computer and use it in GitHub Desktop.
Save ridiculousfish/2994621 to your computer and use it in GitHub Desktop.
A thread safe set written in Objective-C
#import <Foundation/Foundation.h>
@interface SafeSet : NSObject {
NSMutableSet *set;
dispatch_queue_t queue;
}
@end
@implementation SafeSet
- (id)init {
self = [super init];
set = [NSMutableSet new];
queue = dispatch_queue_create("Safe Set", NULL);
return self;
}
- (void)dealloc {
dispatch_release(queue);
}
- (void)add:(id)val {
dispatch_async(queue, ^{
[set addObject:val];
});
}
- (void)remove:(id)val {
dispatch_async(queue, ^{
[set removeObject:val];
});
}
- (BOOL)contains:(id)val {
__block BOOL result;
dispatch_sync(queue, ^{
result = [set containsObject:val];
});
return result;
}
@end
int main(void) {
@autoreleasepool {
SafeSet *set = [SafeSet new];
[set add:@"First"];
[set add:@"Second"];
[set add:@"Third"];
BOOL result = [set contains:@"Third"];
printf("%s\n", result ? "True" : "False");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment