一、GCD几种常用方法:
1、界面UI操作GCD
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // 耗时的操作 dispatch_async(dispatch_get_main_queue(), ^{ // 更新界面 }); });
2、多线程同时执行任务不同步骤
//创建多线程队列 dispatch_queue_t myQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_group_t group=dispatch_group_create(); dispatch_group_async(group, myQueue, ^{ //多线程执行内容 });
dispatch_group_async(group, myQueue, ^{ //多线程执行内容 });
//等待信号 等待上述所有group线程结束 dispatch_group_wait(group, DISPATCH_TIME_FOREVER); dispatch_release(group); dispatch_release(myQueue);
3、简单分离多线程操作先后顺序
dispatch_queue_t queue = dispatch_queue_create("wait", DISPATCH_QUEUE_CONCURRENT); dispatch_async(queue, ^{ NSLog(@"dispatch_async1"); }); dispatch_async(queue, ^{ NSLog(@"dispatch_async2"); });
//等待前面线程执行结束 dispatch_barrier_async(queue, ^{ NSLog(@"dispatch_barrier_async"); });
//等待dispach_barrier_async执行结束 dispatch_async(queue, ^{ NSLog(@"dispatch_async3"); });
4、重复执行代码
dispatch_apply(5, globalQ, ^(size_t index) { // 执行5次 });
二、判断内核数目
通过内核数判断是否使用GCD,避免Iphone4等单核手机,多线程执行反而变慢的情况...
//判断内核数 + (unsigned int) countCores { host_basic_info_data_t hostInfo; mach_msg_type_number_t infoCount; infoCount = HOST_BASIC_INFO_COUNT; host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount); return (unsigned int)(hostInfo.max_cpus); }