iOS GCD 控制并发数量

使用

// 控制最高并发树量为18
dispatch_queue_t seedQueue = dispatch_queue_create("seed_run_Queue",  DISPATCH_QUEUE_CONCURRENT);
    dispatch_asyn_limit_count(seedQueue,18, ^{
        [self deCodingAsyncWithData:resData AndSuccess:success AndFailure:failure];
    });

实现

void dispatch_asyn_limit_count(dispatch_queue_t queue,long count, dispatch_block_t block){
    //控制并发数的信号量
    static dispatch_semaphore_t limitSemaphore;
    //专门控制并发等待的线程
    static dispatch_queue_t receiveQueue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        limitSemaphore = dispatch_semaphore_create(count);
        receiveQueue = dispatch_queue_create("decoding_seed", DISPATCH_QUEUE_SERIAL);
    });
    dispatch_async(receiveQueue, ^{
        //若信号量小于0,则会阻塞receiveQueue的线程,控制添加到queue里的任务不会超过count个。
        dispatch_semaphore_wait(limitSemaphore, DISPATCH_TIME_FOREVER);
        dispatch_async(queue, ^{
            if (block) {
                block();
            }
            dispatch_semaphore_signal(limitSemaphore);//block执行完后增加信号量
        });
    });
}

另一种实现

// 控制并发数量
void dispatch_asyn_limit_count(long count, dispatch_block_t block){
    //控制并发数的信号量
    static dispatch_semaphore_t limitSemaphore;
    static dispatch_queue_t receiveQueue;
    // 单利初始化
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        limitSemaphore = dispatch_semaphore_create(count);
        receiveQueue = dispatch_queue_create("decoding_seed", DISPATCH_QUEUE_SERIAL);
    });
    dispatch_async(receiveQueue, ^{
        //若信号量小于0,则会阻塞receiveQueue的线程,控制添加到queue里的任务不会超过count个。
        dispatch_semaphore_wait(limitSemaphore, DISPATCH_TIME_FOREVER);
        if (block) block();
        dispatch_semaphore_signal(limitSemaphore);//block执行完后增加信号量
    });
}

你可能感兴趣的:(iOS GCD 控制并发数量)