用"栅栏函数"实现数据的"多读单写

2018-08-31  本文已影响44人  小苗晓雪

dispatch_barrier_async栅栏函数

#import <Foundation/Foundation.h>

@interface DataCenter : NSObject

#pragma mark - 读数据
- (id)objectForKey:(NSString *)key;

#pragma mark - 写数据
- (void)setObject:(id)obj forKey:(NSString *)key;


@end
#import "DataCenter.h"

@interface DataCenter()

{
    // 定义一个并发队列:
    dispatch_queue_t _concurrent_queue;
    // 用户数据中心, 可能多个线程需要数据访问:
    NSMutableDictionary *_dataCenterDic;
}

@end

// 多读单写模型
@implementation UserCenter

#pragma mark - init
- (id)init
{
    self = [super init];
    if (self)
    {
        // 创建一个并发队列:
        _concurrent_queue = dispatch_queue_create("read_write_queue", DISPATCH_QUEUE_CONCURRENT);
        // 创建数据字典:
        _dataCenterDic = [NSMutableDictionary dictionary];
    }
    return self;
}


#pragma mark - 读数据
- (id)objectForKey:(NSString *)key
{
    __block id obj;
    // 同步读取指定数据:
    dispatch_sync(_concurrent_queue, ^{
        
        obj = [_dataCenterDic objectForKey:key];
        
    });
    return obj;
}

#pragma mark - 写数据
- (void)setObject:(id)obj forKey:(NSString *)key
{
    // 异步栅栏调用设置数据:
    dispatch_barrier_async(_concurrent_queue, ^{
        
        [_dataCenterDic setObject:obj forKey:key];
        
    });
}

@end

愿编程让这个世界更美好

上一篇下一篇

猜你喜欢

热点阅读