Dispatch Queue 之内存中常驻的几个结构
_dispatch_main_q
也就是主要主队列,一定运行在主线程里。
// 6618342 Contact the team that owns the Instrument DTrace probe before renaming this symbol
struct dispatch_queue_s _dispatch_main_q = {
.do_vtable = &_dispatch_queue_vtable, // 相关的操作函数在这里
.do_ref_cnt = DISPATCH_OBJECT_GLOBAL_REFCNT, //表示永远不会被释放
.do_xref_cnt = DISPATCH_OBJECT_GLOBAL_REFCNT, //表示永远不会被释放
.do_suspend_cnt = DISPATCH_OBJECT_SUSPEND_LOCK,
.do_targetq = &_dispatch_root_queues[DISPATCH_ROOT_QUEUE_COUNT / 2],
.dq_label = "com.apple.main-thread",
.dq_running = 1,
.dq_width = 1, // 串行队列
.dq_serialnum = 1,
};
主队列的目标队列时全局队列其中之一。
对应的do_vtable: _dispatch_queue_vtable
即对应的操作函数。
static const struct dispatch_queue_vtable_s _dispatch_queue_vtable = {
.do_type = DISPATCH_QUEUE_TYPE,
.do_kind = "queue",
.do_dispose = _dispatch_queue_dispose,
.do_invoke = (void *)dummy_function_r0, //什么都不做,返回 0
.do_probe = (void *)dummy_function_r0, //什么都不做,返回 0
.do_debug = dispatch_queue_debug,
};
这样子,在调用do_invoke
和 do_probe
时,会返回0.
_dispatch_root_queues
所有队列最终的target queue。
一共有6个 dispatch_queue_s
。
static struct dispatch_queue_s _dispatch_root_queues[] = {
{
.do_vtable = &_dispatch_queue_root_vtable,
.do_ref_cnt = DISPATCH_OBJECT_GLOBAL_REFCNT, //不会被释放
.do_xref_cnt = DISPATCH_OBJECT_GLOBAL_REFCNT,//不会被释放
.do_suspend_cnt = DISPATCH_OBJECT_SUSPEND_LOCK,
.do_ctxt = &_dispatch_root_queue_contexts[0],
.dq_label = "com.apple.root.low-priority",
.dq_running = 2, //偶数,说明不是串行队列
.dq_width = UINT32_MAX, //最大并发数目
.dq_serialnum = 4,
},
....
对应的do_vtable: _dispatch_queue_root_vtable
static const struct dispatch_queue_vtable_s _dispatch_queue_root_vtable = {
.do_type = DISPATCH_QUEUE_GLOBAL_TYPE,
.do_kind = "global-queue",
.do_debug = dispatch_queue_debug,
.do_probe = _dispatch_queue_wakeup_global,
};
即当调用do_probe
时,会调用 _dispatch_queue_wakeup_global
函数,把队列唤醒。
对应的 do_ctxt: _dispatch_root_queue_contexts
dispatch_root_queue_context_s
的定义如下
struct dispatch_root_queue_context_s {
pthread_workqueue_t dgq_kworkqueue;
uint32_t dgq_pending;
uint32_t dgq_thread_pool_size; // 还可以分配的线程池大小
dispatch_semaphore_t dgq_thread_mediator; // 信号量
};
生成时如下:
static struct dispatch_root_queue_context_s _dispatch_root_queue_contexts[] = {
{
.dgq_thread_mediator = &_dispatch_thread_mediator[0],
.dgq_thread_pool_size = MAX_THREAD_COUNT,
},
可见dgq_thread_mediator
对应于另一组常驻内存的变量。
static struct dispatch_semaphore_s _dispatch_thread_mediator[] = {
{
.do_vtable = &_dispatch_semaphore_vtable,
.do_ref_cnt = DISPATCH_OBJECT_GLOBAL_REFCNT,
.do_xref_cnt = DISPATCH_OBJECT_GLOBAL_REFCNT,
},
下起雨,也要勇敢前行