1、dispatch_semaphore_t
步骤 1)、mainSemaphore = dispatch_semaphore_t semaphore = dispatch_semaphore_create(Number);
可设置number信号量,通过设置信号量可是实现控制并发数
2)dispatch_semaphore_signal(mainSemaphore)
信号量加1
3)dispatch_semaphore_wait(mainSemaphore, DISPATCH_TIME_FOREVER);
信号量为0,则等待; 大于等于1则减一后,继续执行
个人认为适合异步任务数量确定的情况
2、dispatch_group_enter dispatch_group_leave
步骤 1)dispatch_group_t group = dispatch_group_create();
2)在异步任务前 dispatch_group_enter(group) ;任务结束时 dispatch_group_leave(group);
3) 在一个(多个)异步任务结束后 dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{ 要执行的任务 }
适合异步任务不确定的情况,使用起来很灵活,但是对于不是按顺序加入到任务队列中的任务就比较麻烦了,也就是说最后才能调用dispatch_group_notify
3、dispatch_group_async
步骤 1)dispatch_group_t dispatchGroup = dispatch_group_create();
2)dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
dispatch_queue_t dispatchQueue = dispatch_queue_create("ted.queue.next1", DISPATCH_QUEUE_CONCURRENT);
3)dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
NSLog(@"任务一完成");
});
dispatch_group_async(dispatchGroup, dispatchQueue, ^(){
NSLog(@"任务二完成");
});
4)dispatch_group_async(dispatchGroup, globalQueue, ^{
NSLog(@"任务三完成");
});
向两个异步队列提交两个任务,任务1和2都完成才会执行任务3
网友评论