Created
June 26, 2012 09:22
-
-
Save ridiculousfish/2994621 to your computer and use it in GitHub Desktop.
A thread safe set written in Objective-C
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 <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