GCD除了多线程的能力,我们常常还会利用栅栏、信号量等功能实现一些特定需求,本文将通过对libdispatch-1173.60.1源码的解读探究他的实现原理。
dispatch_once
通常我们常用GCD的dispatch_once
创建单例,或者某些只执行一次的代码,例如:
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
<#code to be executed once#>
});
那么在底层的原理是怎样的呢?在dispatch_once
函数的底层,是通过dispatch_once_f
实现,先来看看源码
void
dispatch_once_f(dispatch_once_t *val, void *ctxt, dispatch_function_t func)
{
dispatch_once_gate_t l = (dispatch_once_gate_t)val;
#if !DISPATCH_ONCE_INLINE_FASTPATH || DISPATCH_ONCE_USE_QUIESCENT_COUNTER
uintptr_t v = os_atomic_load(&l->dgo_once, acquire);
if (likely(v == DLOCK_ONCE_DONE)) {
return;
}
#if DISPATCH_ONCE_USE_QUIESCENT_COUNTER
if (likely(DISPATCH_ONCE_IS_GEN(v))) {
return _dispatch_once_mark_done_if_quiesced(l, v);
}
#endif
#endif
if (_dispatch_once_gate_tryenter(l)) {
return _dispatch_once_callout(l, ctxt, func);
}
return _dispatch_once_wait(l);
}
这个方法中,首先会将传入的静态变量强转为dispatch_once_gate_t
类型,然后通过os_atomic_load
方法拿到任务标识v
,而通过任务标识v
,代码流程可能会走以下三个分支。
- 如果v等于
DLOCK_ONCE_DONE
,说明这个任务已经执行过了,直接return
- 通过
_dispatch_once_gate_tryenter
锁住当前任务,如果_dispatch_once_gate_tryenter(l)
返回为true
,说明这个任务block没有执行过,这通过_dispatch_once_callout
执行任务block并开锁,同时在_dispatch_once_gate_tryenter(l)
中将这个任务的标识符置为DLOCK_ONCE_DONE
- 如果进入锁失败,说明当前任务正在执行被锁住,则通过
_dispatch_once_wait(l)
进入等待。
dispatch_semaphore
我们常常使用GCD的信号量去实现一些同步的功能。
通常我们是这么使用信号量的。
dispatch_semaphore_t semphore = dispatch_semaphore_create(1);
dispatch_semaphore_wait(semphore, DISPATCH_TIME_FOREVER);
NSLog(@"test");
dispatch_semaphore_signal(semphore);
这里有三个关键函数:dispatch_semaphore_create
、dispatch_semaphore_wait
、dispatch_semaphore_signal
dispatch_semaphore_create
dispatch_semaphore_t
dispatch_semaphore_create(long value)
{
dispatch_semaphore_t dsema;
// If the internal value is negative, then the absolute of the value is
// equal to the number of waiting threads. Therefore it is bogus to
// initialize the semaphore with a negative value.
if (value < 0) {
return DISPATCH_BAD_INPUT;
}
dsema = _dispatch_object_alloc(DISPATCH_VTABLE(semaphore),
sizeof(struct dispatch_semaphore_s));
dsema->do_next = DISPATCH_OBJECT_LISTLESS;
dsema->do_targetq = _dispatch_get_default_queue(false);
dsema->dsema_value = value;
_dispatch_sema4_init(&dsema->dsema_sema, _DSEMA4_POLICY_FIFO);
dsema->dsema_orig = value;
return dsema;
}
这是信号变量的创建过程,这里我们只需要主要,我们将传入的value
传给了dsema_value
成员。
dispatch_semaphore_wait
long
dispatch_semaphore_wait(dispatch_semaphore_t dsema, dispatch_time_t timeout)
{
long value = os_atomic_dec2o(dsema, dsema_value, acquire);
if (likely(value >= 0)) {
return 0;
}
return _dispatch_semaphore_wait_slow(dsema, timeout);
}
这里的代码有几个步骤,首先将传入的信号变量dsema
的dsema_value
进行进行-1操作,如果得到的值value
大于或等于0,则直接返回0表示成功,否则进入_dispatch_semaphore_wait_slow
进入长等待。
dispatch_semaphore_signal
long
dispatch_semaphore_signal(dispatch_semaphore_t dsema)
{
long value = os_atomic_inc2o(dsema, dsema_value, release);
if (likely(value > 0)) {
return 0;
}
if (unlikely(value == LONG_MIN)) {
DISPATCH_CLIENT_CRASH(value,
"Unbalanced call to dispatch_semaphore_signal()");
}
return _dispatch_semaphore_signal_slow(dsema);
}
这里和dispatch_semaphore_wait
相反,首先将dsema
的dsema_value
进行+1操作,如果value
的值大于0,则返回0执行接下来的操作,如果value的值等于LONG_MIN
,则抛出Unbalanced call to dispatch_semaphore_signal()
的异常,如果value
小于等于0,则进入长等待。
dispatch_group
举个例子,我们通常这么使用GCD的调度组
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
NSLog(@"任务1");
});
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
NSLog(@"任务2");
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"任务完成");
});
或者
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"任务1");
dispatch_group_leave(group);
});
dispatch_group_enter(group);
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"任务2");
dispatch_group_leave(group);
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"任务完成");
});
不管哪种方式,进组和出组必须成对出现,如果进组后没有出组,则dispatch_group_notify
的任务不会执行,如果没有进组便出组,则会导致崩溃。
关于调度组原理的探究,可以先看dispatch_group_enter
的源码
void
dispatch_group_enter(dispatch_group_t dg)
{
// The value is decremented on a 32bits wide atomic so that the carry
// for the 0 -> -1 transition is not propagated to the upper 32bits.
uint32_t old_bits = os_atomic_sub_orig2o(dg, dg_bits,
DISPATCH_GROUP_VALUE_INTERVAL, acquire);
uint32_t old_value = old_bits & DISPATCH_GROUP_VALUE_MASK;
if (unlikely(old_value == 0)) {
_dispatch_retain(dg); //
}
if (unlikely(old_value == DISPATCH_GROUP_VALUE_MAX)) {
DISPATCH_CLIENT_CRASH(old_bits,
"Too many nested calls to dispatch_group_enter()");
}
}
其实不用怎么看代码,注释已经帮我解释了,这里将调度组dg
的old_bits
进行-1操作
再来看dispatch_group_leave
void
dispatch_group_leave(dispatch_group_t dg)
{
// The value is incremented on a 64bits wide atomic so that the carry for
// the -1 -> 0 transition increments the generation atomically.
uint64_t new_state, old_state = os_atomic_add_orig2o(dg, dg_state,
DISPATCH_GROUP_VALUE_INTERVAL, release);
uint32_t old_value = (uint32_t)(old_state & DISPATCH_GROUP_VALUE_MASK);
if (unlikely(old_value == DISPATCH_GROUP_VALUE_1)) {
old_state += DISPATCH_GROUP_VALUE_INTERVAL;
do {
new_state = old_state;
if ((old_state & DISPATCH_GROUP_VALUE_MASK) == 0) {
new_state &= ~DISPATCH_GROUP_HAS_WAITERS;
new_state &= ~DISPATCH_GROUP_HAS_NOTIFS;
} else {
// If the group was entered again since the atomic_add above,
// we can't clear the waiters bit anymore as we don't know for
// which generation the waiters are for
new_state &= ~DISPATCH_GROUP_HAS_NOTIFS;
}
if (old_state == new_state) break;
} while (unlikely(!os_atomic_cmpxchgv2o(dg, dg_state,
old_state, new_state, &old_state, relaxed)));
return _dispatch_group_wake(dg, old_state, true);
}
if (unlikely(old_value == 0)) {
DISPATCH_CLIENT_CRASH((uintptr_t)old_value,
"Unbalanced call to dispatch_group_leave()");
}
}
也可以通过注释看出,这里是与enter相反的操作,这里将group的标记进行了+1操作,如果old_value
等于-1,也就是调度组的enter和leave是成对的出现,那么就调用_dispatch_group_wake
进行下一步操作。
static void
_dispatch_group_wake(dispatch_group_t dg, uint64_t dg_state, bool needs_release)
{
uint16_t refs = needs_release ? 1 : 0; //
if (dg_state & DISPATCH_GROUP_HAS_NOTIFS) {
dispatch_continuation_t dc, next_dc, tail;
// Snapshot before anything is notified/woken
dc = os_mpsc_capture_snapshot(os_mpsc(dg, dg_notify), &tail);
do {
dispatch_queue_t dsn_queue = (dispatch_queue_t)dc->dc_data;
next_dc = os_mpsc_pop_snapshot_head(dc, tail, do_next);
_dispatch_continuation_async(dsn_queue, dc,
_dispatch_qos_from_pp(dc->dc_priority), dc->dc_flags);
_dispatch_release(dsn_queue);
} while ((dc = next_dc));
refs++;
}
if (dg_state & DISPATCH_GROUP_HAS_WAITERS) {
_dispatch_wake_by_address(&dg->dg_gen);
}
if (refs) _dispatch_release_n(dg, refs);
}
_dispatch_group_wake
内部通过一个do-while循环,最终调用的是_dispatch_continuation_async
去执行目标任务,而_dispatch_continuation_async
实际就是异步执行任务的方法。
也就是说dispatch_group_leave
是可以唤醒调度组执行最终任务的。
除了dispatch_group_leave
,另一个可以执行目标任务的方法是dispatch_group_notify
,再来看它的实现。
static inline void
_dispatch_group_notify(dispatch_group_t dg, dispatch_queue_t dq,
dispatch_continuation_t dsn)
{
uint64_t old_state, new_state;
dispatch_continuation_t prev;
dsn->dc_data = dq;
_dispatch_retain(dq);
prev = os_mpsc_push_update_tail(os_mpsc(dg, dg_notify), dsn, do_next);
if (os_mpsc_push_was_empty(prev)) _dispatch_retain(dg);
os_mpsc_push_update_prev(os_mpsc(dg, dg_notify), prev, dsn, do_next);
if (os_mpsc_push_was_empty(prev)) {
os_atomic_rmw_loop2o(dg, dg_state, old_state, new_state, release, {
new_state = old_state | DISPATCH_GROUP_HAS_NOTIFS;
if ((uint32_t)old_state == 0) {
os_atomic_rmw_loop_give_up({
return _dispatch_group_wake(dg, new_state, false);
});
}
});
}
}
可以看到,这里也是判断state
是否为0,也就当前调度组dg
进出租是否成对,再通过_dispatch_group_wake
去执行目标任务。
而调度组相关的有另一个方法dispatch_group_async
void
dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq,
dispatch_block_t db)
{
dispatch_continuation_t dc = _dispatch_continuation_alloc();
uintptr_t dc_flags = DC_FLAG_CONSUME | DC_FLAG_GROUP_ASYNC;
dispatch_qos_t qos;
qos = _dispatch_continuation_init(dc, dq, db, 0, dc_flags);
_dispatch_continuation_group_async(dg, dq, dc, qos);
}
接着看关键方法_dispatch_continuation_group_async
static inline void
_dispatch_continuation_group_async(dispatch_group_t dg, dispatch_queue_t dq,
dispatch_continuation_t dc, dispatch_qos_t qos)
{
dispatch_group_enter(dg);
dc->dc_data = dg;
_dispatch_continuation_async(dq, dc, qos, dc->dc_flags);
}
显而易见,这里也有进组的操作,和我们显式写进组出组实际是一样的。
那么他是何时出组的呢?我们可以通过断点调试查看他出组的位置。
搜索_dispatch_client_callout
,可以发现在_dispatch_continuation_with_group_invoke
方法中有调用
static inline void
_dispatch_continuation_with_group_invoke(dispatch_continuation_t dc)
{
struct dispatch_object_s *dou = dc->dc_data;
unsigned long type = dx_type(dou);
if (type == DISPATCH_GROUP_TYPE) {
_dispatch_client_callout(dc->dc_ctxt, dc->dc_func);
_dispatch_trace_item_complete(dc);
dispatch_group_leave((dispatch_group_t)dou);
} else {
DISPATCH_INTERNAL_CRASH(dx_type(dou), "Unexpected object type");
}
}
这里可以发现dispatch_group_leave
这里调用了,所以dispatch_group_async
和dispatch_group_enter
、dispatch_group_leave
的用法本质上其实是一样的。
至此我们可以得出结论,调度的进组和出组以成对的的,当dispatch_group_leave
或者dispatch_group_notify
调用时便会唤醒调度组执行目标任务。