1、介绍两种读写安全方式
需求: 1.同一时间,只能有1个线程进行写的操作 2.同一时间,可以有多个线程进行读的操作 3.同一时间,不能即有写的操作,又有读的操作
2、pthread_rwlock_t 读写专用锁
使用案例
#import "readWriteVC.h"
#import <pthread.h>
@interface readWriteVC ()
@property (assign, nonatomic)pthread_rwlock_t lock;
@end
@implementation readWriteVC
/**
需求:
1.同一时间,只能有1个线程进行写的操作
2.同一时间,可以有多个线程进行读的操作
3.同一时间,不能即有写的操作,又有读的操作
*/
- (void)viewDidLoad {
[super viewDidLoad];
pthread_rwlock_init(&_lock, NULL);
for (int i = 0; i < 10; i++) {
[[[NSThread alloc] initWithTarget:self selector:@selector(read) object:nil] start];
[[[NSThread alloc] initWithTarget:self selector:@selector(write) object:nil] start];
}
}
- (void)read {
pthread_rwlock_rdlock(&_lock);
sleep(1);
NSLog(@"*****read******");
pthread_rwlock_unlock(&_lock);
}
- (void)write {
pthread_rwlock_wrlock(&_lock);
sleep(1);
NSLog(@"-----------write-----------");
pthread_rwlock_unlock(&_lock);
}
- (void)dealloc {
pthread_rwlock_destroy(&_lock);
}
@end
3、异步栅栏函数使用dispatch_barrier_async
#import "dispatchBarrierVC.h"
@interface dispatchBarrierVC ()
@property (strong, nonatomic) dispatch_queue_t queue;
@end
@implementation dispatchBarrierVC
- (void)viewDidLoad {
[super viewDidLoad];
self.queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
for (int i = 0; i < 10; i++) {
[[[NSThread alloc] initWithTarget:self selector:@selector(read) object:nil] start];
[[[NSThread alloc] initWithTarget:self selector:@selector(write) object:nil] start];
}
}
- (void)read {
dispatch_async(self.queue, ^{
sleep(1);
NSLog(@"*****read******");
});
}
- (void)write {
dispatch_barrier_async(self.queue, ^{ // 这个函数,会用栅栏保护起来,保证只是单线程访问
sleep(1);
NSLog(@"-----------write-----------");
});
}
@end
|