多读单写
要想实现多线程的读写安全,必须满足“读读”并发,“读写”、“写写”互斥。即:
同一时间,只能有1个线程进行写的操作
同一时间,允许有多个线程进行读的操作
同一时间,不允许既有写的操作,又有读的操作
iOS中的实现方案:
(1)pthread_rwlock:读写锁
(2)dispatch_barrier_async:异步栅栏调用
pthread_rwlock
等待锁的线程会进入休眠
//初始化
int pthread_rwlock_init(pthread_rwlock_t * __restrict,
const pthread_rwlockattr_t * _Nullable __restrict);
//销毁
int pthread_rwlock_destroy(pthread_rwlock_t * );
//读-加锁
int pthread_rwlock_rdlock(pthread_rwlock_t *);
//读-尝试加锁
int pthread_rwlock_tryrdlock(pthread_rwlock_t *);
//写-加锁
int pthread_rwlock_trywrlock(pthread_rwlock_t *);
//写-尝试加锁
int pthread_rwlock_wrlock(pthread_rwlock_t *);
//解锁
int pthread_rwlock_unlock(pthread_rwlock_t *);
#include <pthread/pthread.h>
- (void)test {
// 初始化锁
pthread_rwlock_init(&_lock, NULL);
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
for(int i = 1; i <= 5; i ++) {
dispatch_async(queue, ^{
[self write:i];
});
dispatch_async(queue, ^{
[self read:i];
});
}
}
- (void)write:(NSInteger)i {
pthread_rwlock_wrlock(&rwLock); //写锁
sleep(5);
NSLog(@"写入:%d", i);
pthread_rwlock_unlock(&rwLock);//解锁
}
- (void)read:(NSInteger)i {
pthread_rwlock_rdlock(&rwLock); //读锁
sleep(5);
NSLog(@"读取:%d", i);
pthread_rwlock_unlock(&rwLock);//解锁
}
- (void)dealloc {
//销毁
pthread_rwlock_destroy(&rwLock);
}
dispatch_barrier_async 异步栅栏
注意:
(1)这个函数传入的并发队列必须是通过dispatch_queue_cretate
自定义的。如果传入的是一个串行队列
或是一个全局的并发队列
,那这个函数便等同于dispatch_async
函数的效果。
(2)读取的时候使用dispatch_sync
,之所以取值时用同步操作,是因为我们明确返回一个值后才去执行后面的方法。
@interface ViewController ()
@property (nonatomic, strong) dispatch_queue_t queue;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.queue = dispatch_queue_create("rw_queue", DISPATCH_QUEUE_CONCURRENT);
for (int i = 0; i < 10; i++) {
dispatch_async(self.queue, ^{
[self read:@"a"];
});
dispatch_async(self.queue, ^{
[self read:@"b"];
});
dispatch_async(self.queue, ^{
[self read:@"c"];
});
// 这个函数传入的并发队列必须通过dispatch_queue_cretate自定义
dispatch_barrier_async(self.queue, ^{
[self write];
});
}
}
- (void)read:(NSString *)str {
sleep(1);
NSLog(@"read:%@",str);
}
- (void)write {
sleep(1);
NSLog(@"write");
}
@end