GCD方式,关键是信号量的三个重要用法:
创建信号量为0dispatch_semaphore_t sema = dispatch_semaphore_create(0);
进入信号量dispatch_semaphore_signal(sema);
这里请求信号量 +1 为1
等待信号量dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
走到这里如果信号量为0 则不再执行下面的代码 一直等待 信号量不是0 出现 才会执行下面代码,然后信号量为 - 1
//创建线程池
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//创建group
dispatch_group_t group = dispatch_group_create();
//创建信号量
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
for (int i = 0; i < 10; i++) {
dispatch_group_async(group, queue, ^{
NSLog(@"task%i",i);
//进入信号量
dispatch_semaphore_signal(sema);
});
//等待信号量
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}
//结束后
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
dispatch_group_async(group, queue, ^{
NSLog(@"task11");
//进入信号量
});
});
网友评论