iOS 线程同步 NSLock、NSRecursiveLock、NSCondition、NSConditionLock
#import "ViewController.h" #import <pthread.h> @interface ViewController () @property (nonatomic, strong) NSCondition *lock; @property (nonatomic, strong) NSMutableArray *data; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.lock = [[NSCondition alloc]init]; self.data = [NSMutableArray array]; [self test]; // Do any additional setup after loading the view. } //同时执行 删除 添加操作 -(void)test{ [[[NSThread alloc]initWithTarget:self selector:@selector(add) object:nil] start]; [[[NSThread alloc]initWithTarget:self selector:@selector(remove) object:nil] start]; } -(void)add{ sleep(1); [self.lock lock]; [self.data addObject:@"A"]; NSLog(@"添加数据"); //发送信号通知条件能继续往下执行 [self.lock signal]; //广播信号 对应的条件能往下继续执行了 // [self.lock broadcast]; [self.lock unlock]; } -(void)remove{ NSLog(@"开始删除数据"); [self.lock lock]; if (self.data.count==0) { //这时候会等待条件、并且打开当前锁、 //收到条件信号之后会重新加锁并执行后面的代码 [self.lock wait]; } [self.data removeLastObject]; [self.lock unlock]; NSLog(@"删除数据"); }
#import "ViewController.h" @interface ViewController () @property (nonatomic, strong) NSConditionLock *lock; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.lock=[[NSConditionLock alloc]initWithCondition:1]; [[[NSThread alloc]initWithTarget:self selector:@selector(one) object:nil] start]; [[[NSThread alloc]initWithTarget:self selector:@selector(two) object:nil] start]; [[[NSThread alloc]initWithTarget:self selector:@selector(three) object:nil] start]; // Do any additional setup after loading the view. } -(void)one{ //条件依赖,当满足Condition为1时才会解锁 否 则会等待条件满足时进行加锁 [self.lock lockWhenCondition:1]; NSLog(@"one"); [self.lock unlockWithCondition:2]; } -(void)two{ [self.lock lockWhenCondition:2]; NSLog(@"two"); [self.lock unlockWithCondition:3]; } -(void)three{ [self.lock lockWhenCondition:3]; NSLog(@"three"); [self.lock unlock]; } @end