IOS GCD的用法

后台执行:

dispatch_async(dispatch_get_global_queue(0,0),^{

//something

});

主线程执行:

dispatch_async(dispatch_get_main_queue(),^{

//something

});

一次性执行:

staticdispatch_once_tonceToken;dispatch_once(&onceToken,^{

//code to be executed

});

延迟2秒执行:

double delayInseconds =2.0f;

dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW,delayInseconds * NSEC_PER_SEC);

dispatch_after(popTime,dispatch_get_main_queue(),^(void){

//code to be executed on the main queue after delay

})

dispatch_queue_t也可以自己定义,如果要定义queue,可以使用dispatch_queue_create方法,示例如下:

dispatch_queue_t urls_queue = dispatch_queue_create("blog.ddapps.tolly",NULL);

dispatch_async(urls_queue,^{

//your code

});

dispatch_release(urls_queue);

GCD还有一些高级用法,例如让后台两个线程并行执行,然后等两个线程都结束后,再汇 总执行结果。这个可以用dispatch_group 、dispatch_group_async和dispatch_group_notify来实现,示例如下:

dispatch_group_tgroup = dispatch_group_create();

dispatch_group_async(group,dispatch_get_global_queue(0,0),^{

//并行执行的线程一

});

dispatch_group_async(group,dispatch_get_globale_queue(0,0),^{

//并行执行的线程二

});

dispatch_group_notify(group,dispatch_get_global_queue(0,0),^{

//汇总结果

})

你可能感兴趣的:(IOS GCD的用法)