• Read-write lock

// // viewController. m // Multi-read single-write Demo // // Created by Jason on 2019/3/20. // Copyright © 2019 AIA Innovation Information. All rights reserved. //#import "ViewController.h"
#import <pthread.h>

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

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    pthread_rwlock_init(&_lock,NULL);
    for (int i = 0; i< 10; i++) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [self read];
        });
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [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);
}
@endCopy the code
  • The fence operation
// // viewController. m // Multi-read single-write Demo // // Created by Jason on 2019/3/20. // Copyright © 2019 AIA Innovation Information. All rights reserved. //#import "ViewController.h"
#import <pthread.h>@interface ViewController () @property (nonatomic,assign)pthread_rwlock_t lock; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; Dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
    for (int i = 0; i < 10; i++) {
        dispatch_async(queue, ^{
            [self read];
        });
        dispatch_async(queue, ^{
            [self read];
        });
        dispatch_barrier_async(queue, ^{
            [self write];
        });
    }
}

- (void)readWrite{
    pthread_rwlock_init(&_lock,NULL);
    for (int i = 0; i< 10; i++) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [self read];
        });
        
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [self write];
        });
    }
    
}

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

- (void)write {
    pthread_rwlock_wrlock(&_lock);
    NSLog(@"write----");
    sleep(1);
    pthread_rwlock_unlock(&_lock);
}

- (void)dealloc {
    pthread_rwlock_destroy(&_lock);
}
@end
Copy the code