构建一个线程安全的字典

2020-03-21  本文已影响0人  Cocojiang


线程安全锁字典ConcurrentDictionary(并发字典)

ConcurrentDictionary的写操作比使用锁的字典Dictionary要慢得多,而读操作要快一些。因此如果对字典需要大量的线程安全的读操作,ConcurrentDictionary性能比较好。

使用单线程时,并发字典ConcurrentDictionary性能不及Dictionary,但是扩展到5到6个线程,并发字典性能会更好。

如果自己设计 则要+队列+同步 这样才能保证线程安全。。

/**

线程安全的字典

/**

线程安全的字典

*/

@interface OSSSyncMutableDictionary : NSObject

@property (nonatomic, strong) NSMutableDictionary *dictionary;

@property (nonatomic, strong) dispatch_queue_t dispatchQueue;

- (id)objectForKey:(id)aKey;

- (NSArray *)allKeys;

- (void)setObject:(id)anObject forKey:(id <NSCopying>)aKey;

- (void)removeObjectForKey:(id)aKey;

@end

@implementation OSSSyncMutableDictionary

- (instancetype)init {

    if (self = [super init]) {

        _dictionary = [NSMutableDictionary new];

        _dispatchQueue = dispatch_queue_create("com.aliyun.aliyunsycmutabledictionary", DISPATCH_QUEUE_SERIAL);

    }

    return self;

}

- (NSArray *)allKeys {

    __block NSArray *allKeys = nil;

    dispatch_sync(self.dispatchQueue, ^{

        allKeys = [self.dictionary allKeys];

    });

    return allKeys;

}

- (id)objectForKey:(id)aKey {

    __block id returnObject = nil;

    dispatch_sync(self.dispatchQueue, ^{

        returnObject = [self.dictionary objectForKey:aKey];

    });

    return returnObject;

}

- (void)setObject:(id)anObject forKey:(id <NSCopying>)aKey {

    dispatch_sync(self.dispatchQueue, ^{

        [self.dictionary setObject:anObject forKey:aKey];

    });

}

- (void)removeObjectForKey:(id)aKey {

    dispatch_sync(self.dispatchQueue, ^{

        [self.dictionary removeObjectForKey:aKey];

    });

}

@end

上一篇 下一篇

猜你喜欢

热点阅读