我在 GCD 中实现了这个读写器锁,但在并行测试中失败了。我可以解释为什么它失败了吗?
这是用于 iOS 开发的。该代码基于Objective C。我在GCD中编写了一个带有读/写锁的RWCache,用于数据保护。
@interface RWCache : NSObject
- (void)setObject:(id)object forKey:(id <NSCopying>)key;
- (id)objectForKey:(id <NSCopying>)key;
@end
@interface RWCache()
@property (nonatomic, strong) NSMutableDictionary *memoryStorage;
@property (nonatomic, strong) dispatch_queue_t storageQueue;
@end
@implementation RWCache
- (instancetype)init {
self = [super init];
if (self) {
_memoryStorage = [NSMutableDictionary new];
_storageQueue = dispatch_queue_create("Storage Queue", DISPATCH_QUEUE_CONCURRENT);
}
return self;
}
- (void)setObject:(id)object forKey:(id <NSCopying>)key {
dispatch_barrier_async(self.storageQueue, ^{
self.memoryStorage[key] = object;
});
}
- (id)objectForKey:(id <NSCopying>)key {
__block id object = nil;
dispatch_sync(self.storageQueue, ^{
object = self.memoryStorage[key];
});
return object;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
RWCache *cache = [RWCache new];
dispatch_queue_t testQueue = dispatch_queue_create("Test Queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
for (int i = 0; i < 100; i++) {
dispatch_group_async(group, testQueue, ^{
[cache setObject:@(i) forKey:@(i)];
});
dispatch_group_async(group, testQueue, ^{
[cache objectForKey:@(i)];
});
}
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
}
return 0;
}
如果没有死锁,程序会退出0,否则程序会挂起不退出。