iOS gcd dispatch_semaphore_t(信号量)剖析

-(void)dispatchSignal{
    //crate的value表示,最多几个资源可访问
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(2);   
    dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
     
    //任务1
    dispatch_async(quene, ^{
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        NSLog(@"run task 1");
        sleep(1);
        NSLog(@"complete task 1");
        dispatch_semaphore_signal(semaphore);       
    });
//任务2 dispatch_async(quene, ^{ dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); NSLog(@"run task 2"); sleep(1); NSLog(@"complete task 2"); dispatch_semaphore_signal(semaphore); });
//任务3 dispatch_async(quene, ^{ dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); NSLog(@"run task 3"); sleep(1); NSLog(@"complete task 3"); dispatch_semaphore_signal(semaphore); }); }
511196-20170111164237931-1818878873.png

总结:由于设定的信号值为2,先执行两个线程,等执行完一个,才会继续执行下一个,保证同一时间执行的线程数不超过2。

这里我们扩展一下,假设我们设定信号值=1
dispatch_semaphore_create(1)

那么结果就是:


如果设定信号值=3
dispatch_semaphore_create(3)

那么结果就是:


iOS gcd dispatch_semaphore_t(信号量)剖析_第1张图片

其实设定为3,就是不限制线程执行了,因为一共才只有3个线程。

你可能感兴趣的:(iOS gcd dispatch_semaphore_t(信号量)剖析)