美文网首页
用"栅栏函数"实现数据的"多读单写

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

作者: 小苗晓雪 | 来源:发表于2018-08-31 16:45 被阅读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
    

    愿编程让这个世界更美好

    相关文章

      网友评论

          本文标题:用"栅栏函数"实现数据的"多读单写

          本文链接:https://www.haomeiwen.com/subject/zsqewftx.html