iOS 线程同步 NSLockNSRecursiveLockNSCondition

Posted ZhangShengjie

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS 线程同步 NSLockNSRecursiveLockNSCondition相关的知识,希望对你有一定的参考价值。

 

#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

 

以上是关于iOS 线程同步 NSLockNSRecursiveLockNSCondition的主要内容,如果未能解决你的问题,请参考以下文章

iOS开发系列-线程同步技术

iOS 线程同步 NSLockNSRecursiveLockNSCondition

iOS 线程锁同步机制

iOS 线程同步 自旋锁 OSSpinLock

起底多线程同步锁(iOS)

ios多线程同步异步、串行并行队列、死锁