您的位置:首页 > 其它

队列barrier

2016-06-12 10:25 337 查看
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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: