Brief Introduction
-
Serial Dispatch Queue -- 线程池只提供一个线程用来执行任务,所以后一个任务必须等到前一个任务执行结束才能开始。 -
Concurrent Dispatch Queue -- 线程池提供多个线程来执行任务,所以可以按序启动多个任务并发执行。
1. Basic Management
- dispatch_queue_t
serialQ = dispatch_queue_create("eg.gcd.SerialQueue", DISPATCH_QUEUE_SERIAL); - dispatch_async(serialQ,
^{ -
// Code here - });
- dispatch_release(serialQ);
-
- dispatch_queue_t
concurrentQ = dispatch_queue_create("eg.gcd.ConcurrentQueue", DISPATCH_QUEUE_CONCURRENT); - dispatch_async(concurrentQ,
^{ -
// Code here - });
- dispatch_release(concurrentQ);
- dispatch_queue_t
globalQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); - dispatch_queue_t
mainQ = dispatch_get_main_queue();
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
0), ^{ -
// long-running task -
dispatch_async(dispatch_get_main_queue(), ^{ -
// update UI -
}); - });
- dispatch_queue_t
exampleQueue = dispatch_queue_create("com.example.unique.identifier", NULL ); - dispatch_sync(
exampleQueue,^{ -
dispatch_sync( exampleQueue,^{ -
printf("I am now deadlocked...\n"); -
});}); - dispatch_release(
exampleQueue );
2. Normal Control
- dispatch_once
- static
dispatch_once_t onceToken; - dispatch_once(&onceToken,
^{ -
// code to be executed once - });
- dispatch_after
- 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 - });
- dispatch_set_target_queue
- dispatch_set_target_queue(serialQ,
globalQ);
- dispatch_apply
- dispatch_apply(10,
globalQ, ^(size_t index) { -
// do sth. 10 times - });
- dispatch group
- dispatch_group_t
group = dispatch_group_create(); - dispatch_group_async(group,
concurrentQ, blk0); - dispatch_group_async(group,
concurrentQ, blk1); - dispatch_group_async(group,
concurrentQ, blk2); - dispatch_group_notify(group,
mainQ, ^{ -
// update UI - });
- dispatch_release(group);
- dispatch_time_t
time = dispatch_time(DISPATCH_TIME_NOW, 1ull * NSEC_PER_SEC); - dispatch_group_wait(group,
time);
- dispatch_barrier_async
- dispatch_async(concurrentQ,
blk0); - dispatch_async(concurrentQ,
blk1); - dispatch_barrier_async(concurrentQ,
blk_barrier); - dispatch_async(concurrentQ,
blk2);
这份官方文档很清晰地按功能为GCD相关函数进行了分类。
Jason Lee @ Hangzhou