GCD实现多读单写

#import "WHObject.h"

@interface WHObject()

@property (nonatomic, strong) dispatch_queue_t dictQueue;//并发队列
@property (nonatomic, strong) NSMutableDictionary *dict;//可变字典

@end

@implementation WHObject

- (instancetype)init {
    if(self = [super init]) {
        _dictQueue = dispatch_queue_create("com.huangwenhong.queue", DISPATCH_QUEUE_CONCURRENT);
        _dict = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)huangwenhongmethod {
    self.target = [NSObject new];
}

- (id)valueForKey:(NSString *)key {
    id __block obj;
    dispatch_sync(_dictQueue, ^{//因为有数据 return,所以这里是同步调用
        obj = [self.dict valueForKey:key];
    });
    return obj;
}

- (void)setObject:(id)obj forKey:(id<NSCopying>)key {
    //重点:dispatch_barrier_async(),异步栅栏调用;
    //只有提交到并行队列才有意义
    dispatch_barrier_async(_dictQueue, ^{
        [self.dict setObject:obj forKey:key];
    });
}
@end

总结:首先栈栏函数的作用,是执行到当前位置,前面的全部任务都要等待,等待block内部任务执行完成后,继续执行其他任务。(面试时候的问题,用锁不知道能不能实现)

posted @ 2020-03-06 20:17  do+better  阅读(810)  评论(0编辑  收藏  举报