需求:
1.同一时间,只能有1个线程进行写的 *** 作
2.同一时间,可以有多个线程进行读的 *** 作
3.同一时间,不能即有写的 *** 作,又有读的 *** 作
使用案例
#import "readWriteVC.h"
#import
@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
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)