多线程读写安全

多读单写

要想实现多线程的读写安全,必须满足“读读”并发,“读写”、“写写”互斥。即:

同一时间,只能有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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、前言 在前面我们已经讲过了iOS中的线程同步技术,主要通过加锁实现。对于读写操作,一般都比较耗时耗性能,为了保...
    ychen3022阅读 1,761评论 0 0
  • 本文源自本人的学习记录整理与理解,其中参考阅读了部分优秀的博客和书籍,尽量以通俗简单的语句转述。引用到的地方如有遗...
    水中的蓝天阅读 1,331评论 0 3
  • 多线程31-读写安全01-简介 文件操作(IO操作)读取文件往文件中写入内容不能允许读取和写入同时进行我们之前做的...
    越天高阅读 843评论 0 1
  • 读写操作一般都是比较耗时的操作,为了保证读写安全,同时提升性能,一般采取“多读单写”模式.即对同一资源,同一时间,...
    alilialili阅读 938评论 0 0
  • 一、atomic atomic用于保证属性setter、getter的原子性操作,相当于在getter和sette...
    happy神悦阅读 1,268评论 0 1