pthread_rwlock

2016-12-26  本文已影响0人  张霸天

读写锁,在对文件进行操作的时候,写操作是排他的,一旦有多个线程对同一个文件进行写操作,后果不可估量,但读是可以的,多个线程读取时没有问题的。

// 初始化
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER
// 读模式
pthread_rwlock_wrlock(&lock);
// 写模式
pthread_rwlock_rdlock(&lock);
// 读模式或者写模式的解锁
pthread_rwlock_unlock(&lock);

dispatch_async(dispatch_get_global_queue(0, 0), ^{

    [self readBookWithTag:1];
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{

    [self readBookWithTag:2];
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{

    [self writeBook:3];
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{

    [self writeBook:4];
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{

    [self readBookWithTag:5];
});

- (void)readBookWithTag:(NSInteger )tag {
    pthread_rwlock_rdlock(&rwLock);
    NSLog(@"start read ---- %ld",tag);
    self.path = [[NSBundle mainBundle] pathForResource:@"1" ofType:@".doc"];
    self.contentString = [NSString stringWithContentsOfFile:self.path encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"end   read ---- %ld",tag);
    pthread_rwlock_unlock(&rwLock);
}

- (void)writeBook:(NSInteger)tag {
    pthread_rwlock_wrlock(&rwLock);
    NSLog(@"start wirte ---- %ld",tag);
    [self.contentString writeToFile:self.path atomically:YES encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"end   wirte ---- %ld",tag);
    pthread_rwlock_unlock(&rwLock);
}

start   read ---- 1 
start   read ---- 2 
end    read ---- 1 
end    read ---- 2 
start   wirte ---- 3 end    
wirte ---- 3 
start   wirte ---- 4 
end    wirte ---- 4 
start   read ---- 5 
end    read ---- 5
上一篇 下一篇

猜你喜欢

热点阅读