zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    Angularjs 设置全局变量的3种方法
    prevent to do sth 与 prevent sb (from) doing 用法
    软件测试技术对程序员的重要性
    Javascript中setTimeout()以及clearTimeout( )的使用
    Javascript异步编程的常用方法
    软件设计原则总结
    为sublime Text3 安装插件JS Format
    javascript中 if(变量)和if(变量==true)的区别
    Ping 命令
    ipconfig
  • 原文地址:https://www.cnblogs.com/ZhangShengjie/p/12289323.html
Copyright © 2011-2022 走看看