NSMultiReadUniWriteLock

From iPhone Development Wiki
Jump to: navigation, search

NSMultiReadUniWriteLock is an Objective-C wrapper of the POSIX read-write lock (pthread_rwlock_t), for example,

@interface threadSafeMutableDictionary {
  NSMutableDictionary* _dict;
  NSMultiReadUniWriteLock* _rwlock;
}
-(void)setObject:(id)obj forKey:(id)key;
-(id)objectForKey:(id)key;
...
@end

@implementation threadSafeMutableDictionary
-(id)init {
  if ((self = [super init])) {
    _rwlock = [[NSMultiReadUniWriteLock alloc] init];
    ...
  }
  return self;
}
...
-(void)setObject:(id)obj forKey:(id)key {
  [_rwlock lockForWriting];
  [_dict setObject:obj forKey:key];
  [_rwlock unlock];
}
-(id)objectForKey:(id)key {
  [_rwlock lockForReading];
  id obj = [_dict objectForKey:key];
  [_rwlock unlock];
  return obj;
}
@end

Note that -lockForReadingBeforeDate: and -lockForWritingBeforeDate: are currently implemented as a no-op.

References