GCD Source Analysis 5 - dispatch_semaphore

Preface

GCD Semaphore

dispatch_semaphore_t

dispatch_semaphore_s is a semaphore object whose performance is slightly lower than a spin lock. It is used to ensure safe access to shared resources.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
DISPATCH_DECL(dispatch_semaphore);

#define DISPATCH_DECL(name) typedef struct name##_s *name##_t;

struct dispatch_semaphore_s {
DISPATCH_STRUCT_HEADER(dispatch_semaphore_s, dispatch_semaphore_vtable_s);
long dsema_value; // current semaphore value; when this is below 0, the locked resource cannot be accessed
long dsema_orig; // initial semaphore value; limits how many threads can access the resource at the same time

size_t dsema_sent_ksignals; // Mach signals may wake unexpectedly, so atomic operations are used to avoid false signals

semaphore_t dsema_port;
semaphore_t dsema_waiter_port;
size_t dsema_group_waiters;
struct dispatch_sema_notify_s *dsema_notify_head;
struct dispatch_sema_notify_s *dsema_notify_tail;
};
    1. semaphore_t is a mach_port_t semaphore.
1
typedef mach_port_t semaphore_t;
    1. dispatch_sema_notify_s is defined as follows:
1
2
3
4
5
6
struct dispatch_sema_notify_s {
struct dispatch_sema_notify_s *dsn_next;
dispatch_queue_t dsn_queue;
void *dsn_ctxt;
void (*dsn_func)(void *);
};

It still looks scattered at this point, so let’s keep reading.

dispatch_semaphore_create

This creates a counting semaphore with an initial value. If two threads need to finish one job together, you can use a semaphore whose initial value is 0. If you need to manage a limited resource pool, use an initial value equal to the size of the resource pool. When the semaphore is no longer used, call dispatch_release to destroy it and release its memory. Under ARC this is not needed, because the system releases it automatically.

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
dispatch_semaphore_t dispatch_semaphore_create(long value){
dispatch_semaphore_t dsema;

if (value < 0) {
return NULL;
}
// Allocate memory.
dsema = calloc(1, sizeof(struct dispatch_semaphore_s));

if (fastpath(dsema)) {
// do_vtable mainly contains operation functions for dispatch_semaphore_s.
dsema->do_vtable = &_dispatch_semaphore_vtable;

// This can be understood as the end marker of a linked list.
dsema->do_next = DISPATCH_OBJECT_LISTLESS;

// Reference counts.
dsema->do_ref_cnt = 1;
dsema->do_xref_cnt = 1;

// Target queue.
dsema->do_targetq = dispatch_get_global_queue(0, 0);

// Semaphore values.
dsema->dsema_value = value;
dsema->dsema_orig = value;
}

return dsema;
}

The flow is:

  1. value must be greater than or equal to 0.
  2. Allocate memory for a dispatch_semaphore_s and initialize it to 0.
  3. Point dsema->do_vtable to _dispatch_semaphore_vtable, which is defined as follows:
1
2
3
4
5
6
const struct dispatch_semaphore_vtable_s _dispatch_semaphore_vtable = {
.do_type = DISPATCH_SEMAPHORE_TYPE,
.do_kind = "semaphore",
.do_dispose = _dispatch_semaphore_dispose,
.do_debug = _dispatch_semaphore_debug,
};

As the name suggests, _dispatch_semaphore_dispose destroys a semaphore:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void _dispatch_semaphore_dispose(dispatch_semaphore_t dsema){
kern_return_t kr;

if (dsema->dsema_value < dsema->dsema_orig) {
DISPATCH_CLIENT_CRASH("Semaphore/group object deallocated while in use");
}

if (dsema->dsema_port) {
kr = semaphore_destroy(mach_task_self(), dsema->dsema_port);
DISPATCH_SEMAPHORE_VERIFY_KR(kr);
}
if (dsema->dsema_waiter_port) {
kr = semaphore_destroy(mach_task_self(), dsema->dsema_waiter_port);
DISPATCH_SEMAPHORE_VERIFY_KR(kr);
}

_dispatch_dispose(dsema);
}

dispatch_semaphore_wait

This waits on a semaphore, or decreases the semaphore count. Each call decrements the counter by 1. If the counter becomes less than 0 after the decrement, the current thread blocks until a signal is received.

1
2
3
4
5
6
7
8
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 the value is greater than or equal to 0, it means a resource is available and the function returns directly. Otherwise, it calls _dispatch_semaphore_wait_slow and waits for a signal in the FIFO queue until the timeout is reached.

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
static long _dispatch_semaphore_wait_slow(dispatch_semaphore_t dsema, dispatch_time_t timeout){
mach_timespec_t _timeout;
kern_return_t kr;
uint64_t nsec;
long orig;

again:
_dispatch_semaphore_create_port(&dsema->dsema_port);

switch (timeout) {
default:
do {
// timeout() already calculates relative time left
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_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_value) < 0) {
if (dispatch_atomic_cmpxchg(&dsema->dsema_value, orig, orig + 1)) {
return KERN_OPERATION_TIMED_OUT;
}
}
case DISPATCH_TIME_FOREVER:
do {
kr = semaphore_wait(dsema->dsema_port);
} while (kr == KERN_ABORTED);
DISPATCH_SEMAPHORE_VERIFY_KR(kr);
break;
}

goto again;
}

After entering _dispatch_semaphore_wait_slow, the behavior depends on the timeout type:

    1. DISPATCH_TIME_NOW: check immediately and return without waiting. If dsema_value is less than 0, increment it by 1 and return the timeout signal KERN_OPERATION_TIMED_OUT.
    1. DISPATCH_TIME_FOREVER: wait indefinitely until dsema_value becomes greater than 0. Once a signal arrives, it jumps to again and runs the function flow again.
1
2
/* no-timeout code */
kr = semaphore_wait(dsema->dsema_port);
    1. Timed wait: wait until either a signal arrives or the timeout expires.
1
2
/* timeout code */
kr = slowpath(semaphore_timedwait(dsema->dsema_port, _timeout));

dispatch_semaphore_signal

This sends a signal, or increases the count of a semaphore. If the semaphore value before incrementing, dsema_value, is greater than or equal to 0, no thread is blocked by this semaphore, so it returns directly.

1
2
3
4
5
6
DISPATCH_NOINLINE long dispatch_semaphore_signal(dispatch_semaphore_t dsema){
if (dispatch_atomic_inc(&dsema->dsema_value) > 0) {
return 0;
}
return _dispatch_semaphore_signal_slow(dsema);
}

If the semaphore value before incrementing is less than 0, _dispatch_semaphore_signal_slow is called. It wakes one thread waiting in dispatch_semaphore_wait. If multiple threads are waiting, iOS decides which one to wake based on thread priority.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
DISPATCH_NOINLINE static long _dispatch_semaphore_signal_slow(dispatch_semaphore_t dsema){
kern_return_t kr;

_dispatch_semaphore_create_port(&dsema->dsema_port);

// Before dsema_sent_ksignals is incremented we can rely on the reference
// held by the waiter. However, once this value is incremented the waiter
// may return between the atomic increment and the semaphore_signal(),
// therefore an explicit reference must be held in order to safely access
// dsema after the atomic increment.
_dispatch_retain(dsema);

dispatch_atomic_inc(&dsema->dsema_sent_ksignals);

// Use the system semaphore library to send the semaphore signal.
kr = semaphore_signal(dsema->dsema_port);
DISPATCH_SEMAPHORE_VERIFY_KR(kr);

_dispatch_release(dsema);

return 1;
}

Summary

GCD semaphores are relatively simple. Just remember these three key APIs: create, wait, and signal.

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

Title:GCD Source Analysis 5 - dispatch_semaphore

Author:lingyun

Published:2018-02-08 13:08

Updated:2026-09-23 00:37

Original link:https://tsuijunxi.github.io/en/2018/02/08/gcd-source-analysis-5-dispatch-semaphore/

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