dispatch_semaphore_t 多任务按照顺序执行,也就是说单个任务一一执行
NSString *str = @"http://www.jianshu.com/p/6930f335adba";
NSURL *url = [NSURL URLWithString:str];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSession *session = [NSURLSession sharedSession];
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
for (int i=0; i<10; i++) {
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%d---%d",i,i);
dispatch_semaphore_signal(sem);
}];
[task resume];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
}
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"end");
});

dispatch_group_t,如果单个任务依赖于其他多个任务并发完成后才能进行该任务
__block int number = 0;
dispatch_group_t group = dispatch_group_create();
//A耗时操作
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
sleep(3);
number += 2222;
NSLog(@"-----%d", number);
});
//B网络请求
dispatch_group_enter(group);
[self sendRequestWithCompletion:^(id response) {
number += [response integerValue];
NSLog(@"-----%d", number);
dispatch_group_leave(group);
}];
//C网络请求
dispatch_group_enter(group);
[self sendRequestWithCompletion:^(id response) {
number += [response integerValue];
NSLog(@"-----%d", number);
dispatch_group_leave(group);
}];
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"%zd", number + 1000);
});

dispatch_barrier_async 如果多个任务并发依赖于其他多个任务并发执行的结果
dispatch_queue_t queue = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"第一次任务的主线程为: %@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"第二次任务的主线程为: %@", [NSThread currentThread]);
});
dispatch_barrier_async(queue, ^{
NSLog(@"第一次任务, 第二次任务执行完毕, 继续执行");
});
dispatch_async(queue, ^{
NSLog(@"第三次任务的主线程为: %@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"第四次任务的主线程为: %@", [NSThread currentThread]);
});

网友评论