GCD系列是阅读官方文件和在实践中总结的一些常见的GCD用法,基本涉及全部的GCD内容形成的集合文章,文章重点在与精简和全面覆盖。
学习本集合你可以了解:
1. GCD是如何做到多线程调度的
2. 对比其他iOS的多线程方案,GCD的优势和劣势
3. 如何使用GCD相关的API我将在后续不断补充详细内容和实际案例, 欢迎关注,提问和讨论
03-dispatch_after/dispatch_time-延迟调度和操作
04-dispatch_barrier_sync/async-线程阻塞
dispatch_after
延时操作的API,通常Queue会在主线程,但是也可以自定义线程
* @functoin Schedule a block for execution on a given queue at a specified time.
* @param when
* A temporal milestone returned by dispatch_time() or dispatch_walltime().
void dispatch_after(dispatch_time_t when, dispatch_queue_t queue, dispatch_block_t block);
* @param context
* The application-defined context parameter to pass to the function.
*
* @param work
* The application-defined function to invoke on the target queue. The first
* parameter passed to this function is the context provided to
* dispatch_after_f().
* The result of passing NULL in this parameter is undefined.
void dispatch_after_f(dispatch_time_t when, dispatch_queue_t queue, void *_Nullable context, dispatch_function_t work);
dispatch_time
A somewhat abstract representation of time;
where zero means "now" and DISPATCH_TIME_FOREVER means "infinity" and every value in between is an opaque encoding.
typedef uint64_t dispatch_time_t;
#define DISPATCH_TIME_NOW (0ull)
#define DISPATCH_TIME_FOREVER (~0ull)
// Create dispatch_time_t relative to the default clock or modify an existing dispatch_time_t.
//An optional dispatch_time_t to add nanoseconds to. If zero is passed, then dispatch_time() will use the result of mach_absolute_time().
dispatch_time_t dispatch_time(dispatch_time_t when, int64_t delta);
常见用法
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
(int64_t)(60 * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
# 主线程执行代码
});
NSLog(@"你好吗?");
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_queue_create("ll", NULL), ^{
NSLog(@"你好");
});
这里都是一样的,只不过调用的线程种类不一样
2016-11-05 17:10:43.921 Multithreading[16258:488248] 你好吗?
2016-11-05 17:10:47.217 Multithreading[16258:488289] 你好