NSConditionLock
下面是苹果官方文档的说法:
A lock that can be associated with specific, user-defined conditions.
Overview
Using an NSConditionLock
object, you can ensure that a thread can acquire a lock only if a certain condition is met. Once it has acquired the lock and executed the critical section of code, the thread can relinquish the lock and set the associated condition to something new. The conditions themselves are arbitrary: you define them as needed for your application.
下面是个人的理解以及一些例子
#import <Foundation/Foundation.h>
@interface NSLockTest : NSObject
- (void)forTest;
@end
#import "NSLockTest.h"
@interface NSLockTest()
@property (nonatomic,strong) NSMutableArray *tickets;
@property (nonatomic,assign) int soldCount;
@property (nonatomic,strong) NSConditionLock *condition;
@end
@implementation NSLockTest
- (void)forTest
{
self.tickets = [NSMutableArray arrayWithCapacity:1];
self.condition = [[NSConditionLock alloc]initWithCondition:0];
NSThread *windowOne = [[NSThread alloc]initWithTarget:self selector:@selector(soldTicketOne) object:nil];
[windowOne start];
NSThread *windowTwo = [[NSThread alloc]initWithTarget:self selector:@selector(soldTicketTwo) object:nil];
[windowTwo start];
NSThread *windowTuiPiao = [[NSThread alloc]initWithTarget:self selector:@selector(tuiPiao) object:nil];
[windowTuiPiao start];
}
//一号窗口
-(void)soldTicketOne
{
while (YES) {
NSLog(@"====一号窗口没票了,等别人退票");
[self.condition lockWhenCondition:1];
NSLog(@"====在一号窗口买了一张票,%@",[self.tickets objectAtIndex:0]);
[self.tickets removeObjectAtIndex:0];
[self.condition unlockWithCondition:0];
}
}
//二号窗口
-(void)soldTicketTwo
{
while (YES) {
NSLog(@"====二号窗口没票了,等别人退票");
[self.condition lockWhenCondition:2];
NSLog(@"====在二号窗口买了一张票,%@",[self.tickets objectAtIndex:0]);
[self.tickets removeObjectAtIndex:0];
[self.condition unlockWithCondition:0];
}
}
- (void)tuiPiao
{
while (YES) {
sleep(3);
[self.condition lockWhenCondition:0];
[self.tickets addObject:@"南京-北京(退票)"];
int x = arc4random() % 2;
if (x == 1) {
NSLog(@"====有人退票了,赶快去一号窗口买");
[self.condition unlockWithCondition:1];
}else
{
NSLog(@"====有人退票了,赶快去二号窗口买");
[self.condition unlockWithCondition:2];
}
}
}
@end
设计了一个例子,有一号售票窗口和二号售票窗口两个窗口可以买票,也会有一个退票窗口,但是退票窗口随机选择退到一号或者二号售票窗口。
NSConditionLock与NSCondition大体相同,但是NSConditionLock可以设置锁条件,而NSCondition确只是无脑的通知信号。
- (void)lockWhenCondition:(NSInteger)condition;
- (void)unlockWithCondition:(NSInteger)condition;
这两个condition一样的时候会相互通知。
过程
1、初始化 self.condition = [[NSConditionLock alloc]initWithCondition:0];
2、获得锁 [self.condition lockWhenCondition:1];
3、解锁 [self.condition unlockWithCondition:1];