1. 程式人生 > >GCD訊號量控制併發

GCD訊號量控制併發

例程一:控制執行緒數量

    //訊號量控制併發
    dispatch_group_t group = dispatch_group_create();
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(10);
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    for(int i=0;i<100;i++){
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_group_async(group, queue, ^{
            NSLog(@"i=%i",i);
            sleep(2);
            dispatch_semaphore_signal(semaphore);
        });
    }

簡單介紹一下

dispatch_semaphore_create(10): 建立訊號量

dispatch_semaphore_wait(): 同步等待,對訊號量減1效果

dispatch_semaphore_signal(): 對訊號量加1效果

例程二:精細的同步效果

    //訊號量控制併發2
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
    NSMutableArray *array = [[NSMutableArray alloc] init];
    
    for(int i=0;i<1000;i++){
        dispatch_async(queue, ^{
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            [array addObject:[NSNumber numberWithInt:i]];
            NSLog(@"add");
            dispatch_semaphore_signal(semaphore);
        });
    }