GCD方式,關(guān)鍵是信號(hào)量的三個(gè)重要用法:
創(chuàng)建信號(hào)量為0dispatch_semaphore_t sema = dispatch_semaphore_create(0);
進(jìn)入信號(hào)量dispatch_semaphore_signal(sema);
這里請(qǐng)求信號(hào)量 +1 為1
等待信號(hào)量dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
走到這里如果信號(hào)量為0 則不再執(zhí)行下面的代碼 一直等待 信號(hào)量不是0 出現(xiàn) 才會(huì)執(zhí)行下面代碼,然后信號(hào)量為 - 1
//創(chuàng)建線(xiàn)程池
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//創(chuàng)建group
dispatch_group_t group = dispatch_group_create();
//創(chuàng)建信號(hào)量
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
for (int i = 0; i < 10; i++) {
dispatch_group_async(group, queue, ^{
NSLog(@"task%i",i);
//進(jìn)入信號(hào)量
dispatch_semaphore_signal(sema);
});
//等待信號(hào)量
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}
//結(jié)束后
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
dispatch_group_async(group, queue, ^{
NSLog(@"task11");
//進(jìn)入信號(hào)量
});
});