Create a gist now

Instantly share code, notes, and snippets.

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