GCD Source Analysis 4 - dispatch_group

Preface

The analysis focuses on these group APIs:

  • dispatch_group_create
  • dispatch_group_enter
  • dispatch_group_leave
  • dispatch_group_wait
  • dispatch_group_notify
  • dispatch_group_async

dispatch_group_create

This was mentioned once in the opening article, mainly when analyzing the essence of dispatch_group_s. We learned that dispatch_group_t is essentially a semaphore whose value is LONG_MAX. So it is easy to imagine that semaphore behavior is inseparable from the analysis of dispatch_group_t.

1
2
3
4
dispatch_group_t
dispatch_group_create(void){
return (dispatch_group_t)dispatch_semaphore_create(LONG_MAX);
}

The low-level implementation of semaphores is analyzed in a separate article.

dispatch_group_enter

1
2
3
4
void dispatch_group_enter(dispatch_group_t dg){
dispatch_semaphore_t dsema = (dispatch_semaphore_t)dg;
dispatch_semaphore_wait(dsema, DISPATCH_TIME_FOREVER);
}

First, dispatch_group_t is converted into dispatch_semaphore_t, and then dispatch_semaphore_wait is called.

1
2
3
4
5
6
7
long dispatch_semaphore_wait(dispatch_semaphore_t dsema, dispatch_time_t timeout){
// If the semaphore value after -1 is still >= 0, a resource is available.
if (dispatch_atomic_dec(&dsema->dsema_value) >= 0) {
return 0;
}
return _dispatch_semaphore_wait_slow(dsema, timeout);
}

This function atomically decrements the semaphore value. If it is greater than or equal to 0, a resource is available and it returns directly. Otherwise it calls _dispatch_semaphore_wait_slow, waiting for a signal in the FIFO queue until timeout. For details about _dispatch_semaphore_wait_slow, see the dispatch_semaphore article.

Call stack:

1
2
3
dispatch_group_enter
└──dispatch_semaphore_wait
└──_dispatch_semaphore_wait_slow

dispatch_group_leave

1
2
3
4
5
6
7
void dispatch_group_leave(dispatch_group_t dg){
dispatch_semaphore_t dsema = (dispatch_semaphore_t)dg;
dispatch_semaphore_signal(dsema);
if (dsema->dsema_value == dsema->dsema_orig) {
_dispatch_group_wake(dsema);
}
}

This indicates that one block task in the group has completed, and sends a wake-up signal when necessary. In dispatch_group_leave, the group’s semaphore is incremented by 1. Then it checks whether the current semaphore value is equal to the original group semaphore value. If they are equal, it means the tasks are complete, and the wake-up flow _dispatch_group_wake begins.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
long _dispatch_group_wake(dispatch_semaphore_t dsema){

struct dispatch_sema_notify_s *tmp;
struct dispatch_sema_notify_s *head = dispatch_atomic_xchg(&dsema->dsema_notify_head, NULL);
long rval = dispatch_atomic_xchg(&dsema->dsema_group_waiters, 0);
bool do_rel = head;
long kr;

// wake any "group" waiter or notify blocks

if (rval) {
_dispatch_semaphore_create_port(&dsema->dsema_waiter_port);
do {
kr = semaphore_signal(dsema->dsema_waiter_port);
DISPATCH_SEMAPHORE_VERIFY_KR(kr);
} while (--rval);
}
while (head) {
dispatch_async_f(head->dsn_queue, head->dsn_ctxt, head->dsn_func);
_dispatch_release(head->dsn_queue);
do {
tmp = head->dsn_next;
} while (!tmp && !dispatch_atomic_cmpxchg(&dsema->dsema_notify_tail, head, NULL));
free(head);
head = tmp;
}
if (do_rel) {
_dispatch_release(dsema);
}
return 0;
}

_dispatch_group_wake mainly does two things:

  • It wakes semaphores through semaphore_signal.
  • It calls dispatch_async_f in sequence.

Call stack:

1
2
3
4
dispatch_group_leave
└──_dispatch_group_wake
└──semaphore_signal
└──dispatch_async_f

dispatch_group_wait

1
2
3
4
5
6
7
8
9
10
11
12
long dispatch_group_wait(dispatch_group_t dg, dispatch_time_t timeout)
{
dispatch_semaphore_t dsema = (dispatch_semaphore_t)dg;

if (dsema->dsema_value == dsema->dsema_orig) {
return 0;
}
if (timeout == 0) {
return KERN_OPERATION_TIMED_OUT;
}
return _dispatch_group_wait_slow(dsema, timeout);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
DISPATCH_NOINLINE
static long _dispatch_group_wait_slow(dispatch_semaphore_t dsema, dispatch_time_t timeout)
{
mach_timespec_t _timeout;
kern_return_t kr;
uint64_t nsec;
long orig;

again:
// check before we cause another signal to be sent by incrementing dsema->dsema_group_waiters
if (dsema->dsema_value == dsema->dsema_orig) {
return _dispatch_group_wake(dsema);
}
// Mach semaphores appear to sometimes spuriously wake up. Therefore,
// we keep a parallel count of the number of times a Mach semaphore is
// signaled.
dispatch_atomic_inc(&dsema->dsema_group_waiters);
// check the values again in case we need to wake any threads
if (dsema->dsema_value == dsema->dsema_orig) {
return _dispatch_group_wake(dsema);
}

_dispatch_semaphore_create_port(&dsema->dsema_waiter_port);

switch (timeout) {
default:
do {
nsec = _dispatch_timeout(timeout);
_timeout.tv_sec = (typeof(_timeout.tv_sec))(nsec / NSEC_PER_SEC);
_timeout.tv_nsec = (typeof(_timeout.tv_nsec))(nsec % NSEC_PER_SEC);
kr = slowpath(semaphore_timedwait(dsema->dsema_waiter_port, _timeout));
} while (kr == KERN_ABORTED);
if (kr != KERN_OPERATION_TIMED_OUT) {
DISPATCH_SEMAPHORE_VERIFY_KR(kr);
break;
}
case DISPATCH_TIME_NOW:
while ((orig = dsema->dsema_group_waiters)) {
if (dispatch_atomic_cmpxchg(&dsema->dsema_group_waiters, orig, orig - 1)) {
return KERN_OPERATION_TIMED_OUT;
}
}
case DISPATCH_TIME_FOREVER:
do {
kr = semaphore_wait(dsema->dsema_waiter_port);
} while (kr == KERN_ABORTED);
DISPATCH_SEMAPHORE_VERIFY_KR(kr);
break;
}

goto again;
}

Call stack:

1
2
3
4
dispatch_group_wait
└──_dispatch_group_wait_slow
└──semaphore_timedwait
└──semaphore_wait

dispatch_group_notify

1
2
3
void dispatch_group_notify(dispatch_group_t dg, dispatch_queue_t dq, dispatch_block_t db){
dispatch_group_notify_f(dg, dq, _dispatch_Block_copy(db), _dispatch_call_block_and_release);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
void dispatch_group_notify_f(dispatch_group_t dg, dispatch_queue_t dq, void *ctxt, void (*func)(void *)){
dispatch_semaphore_t dsema = (dispatch_semaphore_t)dg;
struct dispatch_sema_notify_s *dsn, *prev;

// FIXME -- this should be updated to use the continuation cache
while (!(dsn = malloc(sizeof(*dsn)))) {
sleep(1);
}

dsn->dsn_next = NULL;
dsn->dsn_queue = dq;
dsn->dsn_ctxt = ctxt;
dsn->dsn_func = func;
_dispatch_retain(dq);

prev = dispatch_atomic_xchg(&dsema->dsema_notify_tail, dsn);
if (fastpath(prev)) {
prev->dsn_next = dsn;
} else {
_dispatch_retain(dg);
dsema->dsema_notify_head = dsn;
if (dsema->dsema_value == dsema->dsema_orig) {
_dispatch_group_wake(dsema);
}
}
}

Call stack:

1
2
3
dispatch_group_notify
└──dispatch_group_notify_f
└──_dispatch_group_wake

dispatch_group_async

First, use this pseudocode to understand the execution flow of dispatch_group_async intuitively:

1
2
3
4
5
6
7
8
9
10
11
/// Pseudocode, for understanding only.
void dispatch_group_async(dispatch_group_t group, dispatch_queue_t queue, dispatch_block_t block)
{
dispatch_retain(group);
dispatch_group_enter(group);
dispatch_async(queue, ^{
block();
dispatch_group_leave(group);
dispatch_release(group);
});
}

The actual source code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void dispatch_group_async(dispatch_group_t dg, dispatch_queue_t dq, dispatch_block_t db){
dispatch_group_async_f(dg, dq, _dispatch_Block_copy(db), _dispatch_call_block_and_release);
}
#endif

void dispatch_group_async_f(dispatch_group_t dg, dispatch_queue_t dq, void *ctxt, void (*func)(void *)){

dispatch_continuation_t dc;

_dispatch_retain(dg);
dispatch_group_enter(dg);

dc = _dispatch_continuation_alloc_cacheonly() ?: _dispatch_continuation_alloc_from_heap();

dc->do_vtable = (void *)(DISPATCH_OBJ_ASYNC_BIT|DISPATCH_OBJ_GROUP_BIT);
dc->dc_func = func;
dc->dc_ctxt = ctxt;
dc->dc_group = dg;

_dispatch_queue_push(dq, dc);
}

dispatch_group_async is a wrapper around dispatch_group_async_f.

Inside dispatch_group_async_f, the main operations are:

  • Call dispatch_group_enter to manage the semaphore reference count.
  • Create a dispatch_continuation_t to record the group the block belongs to, its context, invocation function, and related information.
  • Call _dispatch_queue_push to enqueue the dispatch_continuation_t.

Do you still remember the implementation of dispatch_async_f?

1
2
3
4
5
6
7
8
9
10
11
void dispatch_async_f(dispatch_queue_t dq, void *ctxt, dispatch_function_t func)
{
dispatch_continuation_t dc = fastpath(_dispatch_continuation_alloc_cacheonly());
if (!dc) {
return _dispatch_async_f_slow(dq, ctxt, func);
}
dc->do_vtable = (void *)DISPATCH_OBJ_ASYNC_BIT;
dc->dc_func = func;
dc->dc_ctxt = ctxt;
_dispatch_queue_push(dq, dc);
}

You can see that dispatch_group_async_f and dispatch_async_f are highly similar. The main difference is that dispatch_group_async_f calls dispatch_group_enter first.

At this point, we have only seen the first half of the pseudocode. Where does the second half happen?

It actually corresponds to the logic inside _dispatch_continuation_pop. Pay attention to the last few lines. This article will not analyze _dispatch_continuation_pop in detail; this is only for understanding.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
static inline void _dispatch_continuation_pop(dispatch_object_t dou)
{
dispatch_continuation_t dc = dou._dc;
dispatch_group_t dg;

if (DISPATCH_OBJ_IS_VTABLE(dou._do)) {
return _dispatch_queue_invoke(dou._dq);
}

if ((long)dou._do->do_vtable & DISPATCH_OBJ_ASYNC_BIT) {
_dispatch_continuation_free(dc);
}
if ((long)dou._do->do_vtable & DISPATCH_OBJ_GROUP_BIT) {
dg = dc->dc_group;
} else {
dg = NULL;
}
dc->dc_func(dc->dc_ctxt);
if (dg) {
dispatch_group_leave(dg);
_dispatch_release(dg);
}
}

This function, including _dispatch_queue_push and _dispatch_continuation_pop, was already analyzed in the dispatch_queue article, so the details are not repeated here.

Summary

Many functions called in the group article overlap with the queue article. For repeated parts, refer to the analysis in the queue article.

-------------本文结束 感谢您的阅读-------------
If this article helped you, your support encourages me to keep writing.

Title:GCD Source Analysis 4 - dispatch_group

Author:lingyun

Published:2018-02-06 12:50

Updated:2026-09-23 00:37

Original link:https://tsuijunxi.github.io/en/2018/02/06/gcd-source-analysis-4-dispatch-group/

License: Attribution-NonCommercial-NoDerivatives 4.0 International Please keep the original link and author when sharing.