如何实现多读单写

一.使用GCD实现多读单写
1.dispatch_barrier_async

dispatch_barrier_sync()或者dispatch_barrier_async()入队的block,会等到所有的之前入队的block执行完成后才开始执行。在barrier block后面入队的所有的block,会等到到barrier block本身已经执行完成之后才继续执行。

  • dispatch_barrier 是一个类似于dispatch_async()/dispatch_sync()的API,它可以将barrier block提交到队列中,barrier block 只有提交到自定义的并发队列中才能真正的当做一个栅栏,它在这里起到一个承上启下的作用,只有比它(barrier block)先提交到自定义并发队列的block全部执行完成,它才会去执行,等它执行完成,在它之后添加的block才会继续往下执行。
  • 当dipatch_barrier block没有被提交到自定义的串行队列中,它与dispatch_async()/dispatch_sync()的作用是一样的。

场景需求:需要异步完成三个任务。任务一、任务二、任务三。要求:任务三必须在任务一、任务二完成之后触发。这就需要使用dispatch_barrier_async。
特点:像一堵围墙、成为任务的分割线。

    dispatch_queue_t queue = dispatch_queue_create("myQueue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        //任务1
        for (int i = 0; i < 2; i++) {
            NSLog(@"我是任务一、来自线程:%@",[NSThread currentThread]);
        }
    });
    dispatch_async(queue, ^{
        //任务2
        for (int i = 0; i < 2 ; i++) {
            NSLog(@"我是任务二、来自线程:%@",[NSThread currentThread]);
        }
    });
    
    
    dispatch_barrier_async(queue, ^{
        //栅栏
        for (int i = 0; i < 1 ; i++) {
            NSLog(@"我是分割线、来自线程:%@",[NSThread currentThread]);
        }
    });
    
    dispatch_async(queue, ^{
        //任务3
        for (int i = 0; i < 1 ; i++) {
            NSLog(@"我是任务三、来自线程:%@",[NSThread currentThread]);
        }
    });

2.使用dispatch_barrier_async实现多读单写锁
- (void)test2{
    // 这里必须的自定义的并发队列,不能使用全局并发队列,或者串行队列
    self.queue = dispatch_queue_create("my_quene", DISPATCH_QUEUE_CONCURRENT);
    
    for (int i = 0; i < 10; i++) {
        dispatch_async(self.queue, ^{
            [self read];
        });
        
        dispatch_async(self.queue, ^{
            [self read];
        });
        
        dispatch_async(self.queue, ^{
            [self read];
        });
        
        dispatch_barrier_async(self.queue, ^{
            [self write];
        });
    }
}


- (void)read {
    NSLog(@"read");
}

- (void)write
{
    NSLog(@"write");
}
一.使用pthread_rwlock_t实现多读单写
#import "ViewController.h"
#import 

@interface ViewController ()
@property (assign, nonatomic) pthread_rwlock_t lock;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化锁
    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 read];
        });
        dispatch_async(queue, ^{
            [self write];
        });
    }
}


- (void)read {
    pthread_rwlock_rdlock(&_lock);
    
    NSLog(@"read");
    
    pthread_rwlock_unlock(&_lock);
}

- (void)write
{
    pthread_rwlock_wrlock(&_lock);
    

    NSLog(@"write");
    
    pthread_rwlock_unlock(&_lock);
}

- (void)dealloc
{
    pthread_rwlock_destroy(&_lock);
}


@end
  • pthread_rwlock_rdlock 读取锁
  • pthread_rwlock_wrlock 写入锁
  • pthread_rwlock_destroy 销毁锁

你可能感兴趣的:(如何实现多读单写)