2015-10-29

[iOS] GCD - dispatch


Queues Types:
- Serial Queues
Tasks in serial queues execute one at a time, each task starting only after the preceding task has finished.

- Concurrent Queues
Tasks in concurrent queues are guaranteed to start in the order they were added,
Items can finish in any order and you have no knowledge of the time it will take for the next block to start, nor the number of blocks that are running at any given time.
- Main Queues
Like any serial queue, tasks in this queue execute one at a time. However, it’s guaranteed that all tasks will execute on the main thread, which is the only thread allowed to update your UI. This queue is the one to use for sending messages to UIViews or posting notifications.

- Examples:
// background執行 dispatch_async(dispatch_get_global_queue(0, 0), ^{ // something });
// main thread執行 dispatch_async(dispatch_get_main_queue(), ^{ // something });
// 一次性執行: static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ // code to be executed once });
// delay 2 秒執行 double delayInSeconds = 2.0; 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 });

// 自定義Queue (Serial Queue)
dispatch_queue_t urls_queue = dispatch_queue_create("blog.devtang.com", NULL); dispatch_async(urls_queue, ^{ // your code }); dispatch_release(urls_queue);

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

dispatch_group_t group = dispatch_group_create(); dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{ // 並行執行的 Thread 1 }); dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{ // 並行執行的 Thread 2 }); dispatch_group_notify(group, dispatch_get_global_queue(0,0), ^{ // thread 1 & 2 完成後執行 });