1.读写锁(pthread_rwlock_t)
#import <pthread.h>
@interface TKReadWhiteSafeDic() {
pthread_rwlock_t lock;
dispatch_queue_t concurrent_queue;
NSMutableDictionary *userCenterDic;
}
@end
@implementation TKReadWhiteSafeDic
- (id)init {
self = [super init];
if (self) {
pthread_rwlock_init(&lock,NULL);
userCenterDic = [NSMutableDictionary dictionary];
concurrent_queue = dispatch_queue_create("read_write_queue", DISPATCH_QUEUE_CONCURRENT);
}
return self;
}
- (id)objectForKey:(NSString *)key {
pthread_rwlock_rdlock(&_rwlock);
id obj = [userCenterDic objectForKey:key];
pthread_rwlock_unlock(&_rwlock);
return obj;
}
- (void)setObject:(id)obj forKey:(NSString *)key {
pthread_rwlock_wrlock(&_rwlock);
[userCenterDic setObject:obj forKey:key];
pthread_rwlock_unlock(&_rwlock);
}
2.dispatch_barrie
@interface TKReadWhiteSafeDic() {
dispatch_queue_t concurrent_queue;
NSMutableDictionary *userCenterDic;
}
@end
@implementation TKReadWhiteSafeDic
- (id)init {
self = [super init];
if (self) {
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];
});
}