NSMutableDictionary
- (void)testMutableDictionaryThreadSafe {dispatch_semaphore_t sema = dispatch_semaphore_create(0);dispatch_async(concurrent_queue, ^{
for (int index = 0; index<1000 ; index++) {dict[@(index)] = @(index);
}
dispatch_semaphore_signal(sema);
});
dispatch_async(concurrent_queue, ^{
for
(int index
=
0;
index<1000
;
index++) {
dict[@(index)] = @(0);}
dispatch_semaphore_signal(sema);
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
NSLog(@"dict is %@", dict); }
NSMutableDictionary
gcd
NSMutableDictionary
serial queue + dispatch_async
dispatch_async ,
concurrent queue + dispatch_async
dispatch_barrier_async dispatch_barrier_async dispatch_barrier_async
barrier barrier concurrent queue
typedef void (^ThreadSafeDictionaryBlock)(ThreadSafeDictionary*dict, NSString *key, id object);
@interface ThreadSafeDictionary (){
dispatch_queue_t concurrentQueue; }
@end @implementation ThreadSafeDictionary
- (id)init{
if
(self
= [super
init]) {
concurrentQueue = dispatch_queue_create("www.reviewcode
.cn", DISPATCH_QUEUE_CONCURRENT); }
return self;}
- (void)objectForKey:(id)aKey
block:(ThreadSafeDictionaryBlock)block
{
id
key = [aKey
copy];
__weak
__typeof__(self)
weakSelf = self;dispatch_async(concurrentQueue,
^{
ThreadSafeDictionary *strongSelf = weakSelf;if (!strongSelf)
return;
id
object = [self
objectForKey:key];block(self,
key, object);
});}
- (void)setObject:(id)object
forKey:(NSString
*)key block:(ThreadSafeDictionaryBlock)block
{