问题如下:
- 同一时间, 只能有 1 个线程进行写的操作
- 同一时间, 允许多个线程进行读的操作
- 同一时间, 不允许既有写的操作, 又有读的操作
有专门的锁来处理以上问题: - pthread_rwlock
- dispatch_barrier_async
pthread_rwlock(等待锁)
pthread_rwlock_t lock;
- (void)_rwlock_read {
pthread_rwlock_rdlock(&lock);
NSLog(@"%s", __func__);
pthread_rwlock_unlock(&lock);
}
- (void)_rwlock_write {
pthread_rwlock_wrlock(&lock);
sleep(1);
NSLog(@"%s", __func__);
pthread_rwlock_unlock(&lock);
}
- (void)_rwlock {
pthread_rwlock_init(&lock, NULL);
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
for (int i = 0; i < 10; ++i) {
dispatch_async(queue, ^{
[self _interview08_read];
});
dispatch_async(queue, ^{
[self _interview08_write];
});
}
}
dispatch_barrier_async
会创建一个线程围栏, 保证其内部的操作执行不会被别人抢了, 也就是说, 两个 read 的 log 会同时打印, 而两次 write 的 log 会隔一秒在进行打印
注意:要想使用这个围栏必须由 dispatch_queue_create
来创建这个队列
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
for (int i = 0; i < 10; ++i) {
dispatch_async(queue, ^{
sleep(1);
NSLog(@"%s", "read");
});
dispatch_async(queue, ^{
sleep(1);
NSLog(@"%s", "read");
});
dispatch_barrier_async(queue, ^{
sleep(1);
NSLog(@"%s", "write");
});
dispatch_barrier_async(queue, ^{
sleep(1);
NSLog(@"%s", "write");
});
}
网友评论