在開發(fā)中咕幻,我們經(jīng)常會(huì)用到針對(duì)一個(gè)數(shù)據(jù)存儲(chǔ)的多讀單寫功能滨攻。dispatch_barrier_async就能實(shí)現(xiàn)該功能线得,保證你在讀的過(guò)程中可以多并發(fā)饶唤,寫的過(guò)程中可以阻塞其他操作。
@interface UserCenter()
{
// 定義一個(gè)并發(fā)隊(duì)列
dispatch_queue_t concurrent_queue;
// 用戶數(shù)據(jù)中心, 可能多個(gè)線程需要數(shù)據(jù)訪問(wèn)
NSMutableDictionary *userCenterDic;
}
@end
// 多讀單寫模型
@implementation UserCenter
- (id)init
{
self = [super init];
if (self) {
// 通過(guò)宏定義 DISPATCH_QUEUE_CONCURRENT 創(chuàng)建一個(gè)并發(fā)隊(duì)列
concurrent_queue = dispatch_queue_create("read_write_queue", DISPATCH_QUEUE_CONCURRENT);
// 創(chuàng)建數(shù)據(jù)容器
userCenterDic = [NSMutableDictionary dictionary];
}
return self;
}
- (id)objectForKey:(NSString *)key
{
__block id obj;
// 同步讀取指定數(shù)據(jù)
dispatch_async(concurrent_queue, ^{
obj = [userCenterDic objectForKey:key];
});
return obj;
}
- (void)setObject:(id)obj forKey:(NSString *)key
{
// 異步柵欄調(diào)用設(shè)置數(shù)據(jù)
dispatch_barrier_sync(concurrent_queue, ^{
[userCenterDic setObject:obj forKey:key];
});
}