Objective-C 实现读写锁

读写锁

 

@interface RWLock : NSObject

- (void)readLock;
- (void)readUnlock;
- (void)writeLock;
- (void)writeUnlock;

@end

  

#import "RWLock.h"

@interface RWLock()

@property (nonatomic, assign) NSInteger stat; // == 0 无锁;> 0 已加读锁个数;< 0 已加写锁
@property (nonatomic, strong) NSCondition *cond; // 条件变量

@end

@implementation RWLock

- (id)init {
    if(self = [super init]) {
        self.stat = 0;
        self.cond = [[NSCondition alloc] init];
    }
    return self;
}

- (void)readLock {
    [self.cond lock];
    while (self.stat < 0) { // 已经有写操作,阻塞等待
        [self.cond wait];
    }
    self.stat++; // 增加一个读操作
    [self.cond unlock];
}

- (void)readUnlock {
    [self.cond lock];
    if (--self.stat == 0) { // 减少一个读操作
        [self.cond signal]; // 唤醒一个等待的写操作
    }
    [self.cond unlock];
}

- (void)writeLock {
    [self.cond lock];
    while (self.stat != 0) { // 已经有读写操作,阻塞等待
        [self.cond wait];
    }
    self.stat = -1;
    [self.cond unlock];
}

- (void)writeUnlock {
    [self.cond lock];
    self.stat = 0;
    [self.cond broadcast]; // 唤醒所有读写操作
    [self.cond unlock];
}

@end

 

posted @ 2019-01-23 12:54  happyyoung  阅读(365)  评论(0编辑  收藏  举报