一個(gè)頁面需要同時(shí)發(fā)送網(wǎng)絡(luò)請(qǐng)求A和B 然后需要在AB都返回結(jié)果之后在進(jìn)行操作 寫了個(gè)demo模擬下這種情況
第一種方法dispatch_group_t
控制
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
NSLog(@"網(wǎng)絡(luò)請(qǐng)求1和網(wǎng)絡(luò)請(qǐng)求2同時(shí)發(fā)送病线!");
dispatch_group_enter(group);
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:1];
NSLog(@"網(wǎng)絡(luò)請(qǐng)求1完成");
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:2];
NSLog(@"網(wǎng)絡(luò)請(qǐng)求2完成");
dispatch_group_leave(group);
});
dispatch_group_notify(group, queue, ^{
NSLog(@"網(wǎng)絡(luò)請(qǐng)求1和網(wǎng)絡(luò)請(qǐng)求2都完成镰吆!");
});
這里dispatch_group_enter
和dispatch_group_leave
一定要成對(duì)出現(xiàn) 然后用dispatch_group_notify
等待完成
方法二 信號(hào)量dispatch_semaphore_t
控制
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
NSLog(@"0");
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:1];
NSLog(@"1");
dispatch_semaphore_signal(sem);
});
dispatch_async(queue, ^{
[NSThread sleepForTimeInterval:2];
NSLog(@"2");
dispatch_semaphore_signal(sem);
});
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
NSLog(@"都完成了");
信號(hào)量沒什么好說的 參考文章http://www.reibang.com/p/8fb33b89b5a7
第三種 柵欄塊dispatch_barrier_async
控制
dispatch_queue_t conQueue = dispatch_queue_create("myQueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(conQueue, ^{
[NSThread sleepForTimeInterval:1];
NSLog(@"111");
});
dispatch_async(conQueue, ^{
[NSThread sleepForTimeInterval:2];
NSLog(@"222");
});
dispatch_barrier_async(conQueue, ^{
NSLog(@"333");
});
這里需要注意 要想執(zhí)行完前面所有的任務(wù)再執(zhí)行barrier必須滿足兩個(gè)條件
1幔亥、所有任務(wù)都是在同一個(gè)隊(duì)列中
2粒褒、隊(duì)列不能是全局并行隊(duì)列, 必須是自己創(chuàng)建的隊(duì)列
這只是用GCD的三種簡(jiǎn)單實(shí)現(xiàn) 當(dāng)然還有其他很多方法