1. 程式人生 > >訊號量的簡單使用

訊號量的簡單使用

有些時候我們會遇見需要限制訪問數量或者按一定順序執行方法,就可以使用到。

- (void)test {
    dispatch_semaphore_t sem = dispatch_semaphore_create(1);
    dispatch_queue_t queue = dispatch_queue_create("testBlock", NULL);
    dispatch_async(queue, ^{
        dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"1");
            dispatch_semaphore_signal(sem);
        });
    });
    
    dispatch_async(queue, ^{
        dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
        NSLog(@"2");
        dispatch_semaphore_signal(sem);
    });
    
    dispatch_async(queue, ^{
        dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"3");
            dispatch_semaphore_signal(sem);
        });
    });
    
    dispatch_async(queue, ^{
        dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
        NSLog(@"4");
        dispatch_semaphore_signal(sem);
    });
}

如上面的程式碼,我們可以dispatch_semaphore_t sem = dispatch_semaphore_create(1);這時候訊號值為1,那麼下面的方法就會按順序執行,所以結果會按順序1234輸出。