iOS开发基础85-线程dispatch apply
我们知道遍历数组是一个相对耗时的操作,而同时手机的核是越来越多,所以我们需要充分利用iOS多核的作用.
特别是在遍历操作中还有其他耗时操作.像我们平时直接遍历数组的操作
for (NSInteger i= 0,i< 100,i++){ //do something }
这样的代码不会随着手机的不断升级而提高效率.
但是利用GCD可以实现充分利用多核.并且随着手机不断升级,同样的代码,执行效率会自动提高,十分OK.下面提供两种常用方法.
NSArray * arr = @[@"1",@"2",@"3",@"4",@"5"]; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_group_t group = dispatch_group_create(); for (NSInteger i = 0; i < arr.count; i++) { NSLog(@"%ld",(long)i); dispatch_group_async(group, queue, ^{ sleep(5); NSLog(@"%ld -- %@",(long)i,[NSThread currentThread]); }); } //dispatch_group_wait(group, DISPATCH_TIME_FOREVER);// 等待queue任务执行完,才往下走; dispatch_group_notify(group, queue, ^{ // 往下走,回调block NSLog(@"group end"); }); NSLog(@"end”);
2016-07-26 15:59:09.566 学习之路[4448:1770686] 0
2016-07-26 15:59:09.566 学习之路[4448:1770686] 1
2016-07-26 15:59:09.566 学习之路[4448:1770686] 2
2016-07-26 15:59:09.567 学习之路[4448:1770686] 3
2016-07-26 15:59:09.567 学习之路[4448:1770686] 4
2016-07-26 15:59:09.567 学习之路[4448:1770686] end
2016-07-26 15:59:14.569 学习之路[4448:1772333] 4 -- <NSThread: 0x7fc412631120>{number = 6, name = (null)}
2016-07-26 15:59:14.569 学习之路[4448:1772330] 1 -- <NSThread: 0x7fc4124bf8e0>{number = 2, name = (null)}
2016-07-26 15:59:14.569 学习之路[4448:1771326] 0 -- <NSThread: 0x7fc4126255e0>{number = 3, name = (null)}
2016-07-26 15:59:14.569 学习之路[4448:1772332] 3 -- <NSThread: 0x7fc41261d900>{number = 5, name = (null)}
2016-07-26 15:59:14.569 学习之路[4448:1772331] 2 -- <NSThread: 0x7fc4124bb230>{number = 4, name = (null)}
2016-07-26 15:59:14.570 学习之路[4448:1772331] group end
dispatch group 只能异步,并且不会在主线程走任务
NSArray * arr = @[@"1",@"2",@"3",@"4",@"5"]; dispatch_apply([arr count], dispatch_get_global_queue(0, 0), ^(size_t index) { sleep(1); NSLog(@"%@ %@",arr[index],[NSThread currentThread]); }); NSLog(@"end”);
它以指定的次数将指定的Block加入到指定的队列中,并等待队列中操作全部完成,NSLog(@"end”)在上面任务执行完才会执行
2016-07-26 16:00:58.106 学习之路[4463:1787375] 2 <NSThread: 0x7f98fa61aff0>{number = 4, name = (null)}
2016-07-26 16:00:58.106 学习之路[4463:1787363] 3 <NSThread: 0x7f98fa61e680>{number = 2, name = (null)}
2016-07-26 16:00:58.106 学习之路[4463:1787587] 4 <NSThread: 0x7f98fa747a00>{number = 3, name = (null)}
2016-07-26 16:00:58.106 学习之路[4463:1787047] 1 <NSThread: 0x7f98fa402c30>{number = 1, name = main}
2016-07-26 16:00:59.110 学习之路[4463:1787375] 5 <NSThread: 0x7f98fa61aff0>{number = 4, name = (null)}
2016-07-26 16:00:59.110 学习之路[4463:1787047] end
dispatch apply 是同步的,可以在主线程走任务,如果想异步可以在外面包一层
NSArray * arr = @[@"1",@"2",@"3",@"4",@"5"]; dispatch_async(dispatch_get_global_queue(0, 0), ^{ dispatch_apply([arr count], dispatch_get_global_queue(0, 0), ^(size_t index) { sleep(1); NSLog(@"%@ %@",arr[index],[NSThread currentThread]); }); }); NSLog(@"end"); }