iOS如何判断多个异步线程是否执行完毕
一、添加100个操作,怎么知道执行完了
1、dispatch_group_notify
dispatch_queue_t queue = dispatch_queue_create("jjjjjj", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
for (int i = 0; i<100; i++) {
dispatch_group_async(group, queue, ^{
NSLog(@"%@ %d",[NSThread currentThread],i);
});
}
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"end");
});
2、dispatch_barrier_async
dispatch_queue_t queue = dispatch_queue_create("kkk", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"A");
});
dispatch_async(queue, ^{
NSLog(@"C");
});
dispatch_barrier_async(queue, ^{
NSLog(@"%@",[NSThread currentThread]);
});
3、waitUntilFinished
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"op1");
}];
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"op2");
}];
NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"op3");
}];
[queue addOperations:@[op1,op2,op3] waitUntilFinished:YES];//YES 阻塞
NSLog(@"end");
二、5个线程并发,如何实现
1、GCD控制最大并发数
dispatch_queue_t queue = dispatch_queue_create("hhhhhhh", DISPATCH_QUEUE_CONCURRENT);
dispatch_semaphore_t semaphore = dispatch_semaphore_create(5);
for (int i = 0; i<10; i++) {
dispatch_async(queue, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"%@ %d",[NSThread currentThread],i);
dispatch_semaphore_signal(semaphore);
});
}
2、 maxConcurrentOperationCount属性设置最大并发数(该属性需要在任务添加到队列中之前进行设置)。maxConcurrentOperationCount默认值是-1;如果值设为0,那么不会执行任何任务;如果值设为1,那么该队列是串行的;如果大于1,那么是并行的。
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
queue.maxConcurrentOperationCount = 5;
for (int i =0; i<10; i++) {
NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"%@ %d",[NSThread currentThread],i);
}];
[queue addOperation:op1];
}