for 异步任务需要将当前线程阻挡住,
这个时候考虑到信号量:dispatch_semaphore_t。
但另一个思路:lock行不行呢?如果用nslock呢。在for 外部定于一个lock。循环内开始的是 lock on,异步任务结束后 Lock off。这个思路还没验证。以下的代码是抄袭的。
printf("处理前创建信号量,开始循环异步请求操作\n");
// 1.创建一个串行队列,保证for循环依次执行
dispatch_queue_t serialQueue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);
// 2.异步执行任务
dispatch_async(serialQueue, ^{
// 3.创建一个数目为1的信号量,用于“卡”for循环,等上次循环结束在执行下一次的for循环
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
for (int i = 0; i<5; i++) {
// 开始执行for循环,让信号量-1,这样下次操作须等信号量>=0才会继续,否则下次操作将永久停止
printf("信号量等待中\n");
// 模拟一个异步任务
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://github.com"]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 本次for循环的异步任务执行完毕,这时候要发一个信号,若不发,下次操作将永远不会触发
[tampArray addObject:@(i)];
NSLog(@"本次耗时操作完成,信号量+1 %@\n",[NSThread currentThread]);
dispatch_semaphore_signal(sema);
}];
[dataTask resume];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}
NSLog(@"其他操作");
for (NSNumber *num in tampArray) {
NSLog(@"所有操作完成后的操作---> %@\n",num);
}
});
网友评论