参考文档中一共提到8种锁,讲解的很详细。后续可以抽空继续学习。暂且就其中的两种锁作一简单记录:
NSLock:
//主线程中
NSLock *lock = [[NSLock alloc] init];
//线程1
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[lock lock];
NSLog(@"线程1");
sleep(2);
NSLog(@"线程1解锁成功");
[lock unlock];
});
//线程2
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[lock lock];
NSLog(@"线程2");
sleep(1);
NSLog(@"线程2解锁成功");
[lock unlock];
});
NSConditionLock
//主线程中
NSConditionLock *lock = [[NSConditionLock alloc] initWithCondition:0];
//线程1
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[lock lockWhenCondition:4];
NSLog(@"线程1");
sleep(2);
[lock unlockWithCondition:5];
});
//线程2
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[lock lockWhenCondition:0];
NSLog(@"线程2");
sleep(3);
NSLog(@"线程2解锁成功");
[lock unlockWithCondition:2];
});
//线程3
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[lock lockWhenCondition:2];
NSLog(@"线程3");
sleep(3);
NSLog(@"线程3解锁成功");
[lock unlockWithCondition:3];
});
//线程4
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[lock lockWhenCondition:3];
NSLog(@"线程4");
sleep(2);
NSLog(@"线程4解锁成功");
[lock unlockWithCondition:4];
});
锁是一种常用的同步工具。从代码的角度讲就是加锁时,同一时刻只能有一个锁内代码执行。也可以用来做添加线程依赖。但实测,在网络请求的线程处理时还是得细心处理。