美文网首页
dispatch_barrier_async 多读单写

dispatch_barrier_async 多读单写

作者: 派大星的博客 | 来源:发表于2020-10-20 21:45 被阅读0次
    #import "UserCenter.h"
    
    @interface UserCenter()
    {
        // 定义一个并发队列
        dispatch_queue_t concurrent_queue;
        
        // 用户数据中心, 可能多个线程需要数据访问
        NSMutableDictionary *userCenterDic;
    }
    
    @end
    
    // 多读单写模型
    @implementation UserCenter
    
    - (id)init
    {
        self = [super init];
        if (self) {
            // 通过宏定义 DISPATCH_QUEUE_CONCURRENT 创建一个并发队列
            concurrent_queue = dispatch_queue_create("read_write_queue", DISPATCH_QUEUE_CONCURRENT);
            // 创建数据容器
            userCenterDic = [NSMutableDictionary dictionary];
        }
        
        return self;
    }
    
    - (id)objectForKey:(NSString *)key
    {
        __block id obj;
        // 同步读取指定数据
        dispatch_sync(concurrent_queue, ^{
            obj = [userCenterDic objectForKey:key];
        });
        
        return obj;
    }
    
    - (void)setObject:(id)obj forKey:(NSString *)key
    {
        // 异步栅栏调用设置数据
        dispatch_barrier_async(concurrent_queue, ^{
            [userCenterDic setObject:obj forKey:key];
        });
    }
    
    @end
    

    dispatch_barrier_async:

    • Submits a barrier block for asynchronous execution and returns immediately.

    dispatch_sync

    • Submits a block object for execution and returns after that block finishes executing.

    相关文章

      网友评论

          本文标题:dispatch_barrier_async 多读单写

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