dispatch_semaphore_t信号量

 __block  long signalValue;
    //在dispatch_semaphore_wait和dispatch_semaphore_signal中的数据只能被一个线程访问
    //这在多线程同步中能够防止数据的读写错误
    //传递的参数是信号量最初值,下面例子的信号量最初值是1,这个地方如果传的是0,就会等待,如果>=1就不等待
    dispatch_semaphore_t signal = dispatch_semaphore_create(1);
    
    dispatch_time_t overTime = dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC);
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        // 当信号量是0的时候,dispatch_semaphore_wait(signal, overTime);这句代码会一直等待直到overTime超时.
        //这里信号量是1 所以不会在这里发生等待.每次调用,dispatch_semaphore_wait,信号量的值就会减1,
        signalValue = dispatch_semaphore_wait(signal, overTime);//使信号量值减1
        signalValue = dispatch_semaphore_wait(signal, overTime);
        NSLog(@"first_wiat = %ld",signalValue);
        

        
        NSLog(@"需要线程同步的操作1 开始");
        NSLog(@"需要线程同步的操作1 结束");
        signalValue = dispatch_semaphore_signal(signal);//这句代码会使信号值 增加1
        //并且会唤醒一个线程去开始继续工作,如果唤醒成功,那么返回一个非零的数,如果没有唤醒,那么返回 0
        NSLog(@"first_end = %ld",signalValue);
        
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        
        signalValue =dispatch_semaphore_wait(signal, overTime);
        NSLog(@"first_wiat = %ld",signalValue);
        
        NSLog(@"需要线程同步的操作2");
        
        
        signalValue = dispatch_semaphore_signal(signal);
        
        
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        signalValue = dispatch_semaphore_wait(signal, overTime);
        NSLog(@"first_wiat = %ld",signalValue);
        NSLog(@"需要线程同步的操作3");
        
        signalValue = dispatch_semaphore_signal(signal);
        
        
    });


你可能感兴趣的:(dispatch_semaphore_t信号量)