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
  • 相关阅读:
    MySQL的char和varchar针对空格的处理
    单KEY业务,数据库水平切分架构实践
    接口测试学习笔记1-接口测试的用例设计
    Robot Framework源码解析(2)
    Robot Framework 源码解析(1)
    Python学习笔记1 -- TypeError: 'str' object is not callable
    OKHttp源码学习同步请求和异步请求(二)
    OKHttp源码学习--HttpURLConnection HttpClient OKHttp Get and post Demo用法对比
    Javapoet源码解析
    Universal-Image-Loader源码解解析---display过程 + 获取bitmap过程
  • 原文地址:https://www.cnblogs.com/ZhangShengjie/p/12289323.html
Copyright © 2011-2022 走看看