美文网首页
pthread_rwlock

pthread_rwlock

作者: 张霸天 | 来源:发表于2016-12-26 21:48 被阅读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

相关文章

  • pthread_rwlock

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

  • 读写锁

    pthread_rwlock 读写锁API 读写锁的数据类型为pthread_rwlock_t。如果这个类型的某个...

  • iOS锁-pthread_rwlock

    pthread_rwlock_t API说明 1、pthread_rwlock_init,初始化锁2、pthrea...

  • iOS pthread_rwlock 实现多读单写

    iOS pthread_rwlock 实现多读单写 上面的代码用到了读写锁,读操作是共享的,可以多线程同时读取,写...

网友评论

      本文标题:pthread_rwlock

      本文链接:https://www.haomeiwen.com/subject/vmhsvttx.html