summaryrefslogtreecommitdiff
path: root/libcr_ipc/mutex.c
blob: 1b4e626d3f6269cffe3de5c9998ff89a7e54f982 (plain)
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
/* libcr_ipc/mutex.c - Simple mutexes for libcr
 *
 * Copyright (C) 2024-2025  Luke T. Shumaker <lukeshu@lukeshu.com>
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

#include <libcr/coroutine.h> /* for cid_t, cr_* */
#include <libmisc/assert.h>

#define IMPLEMENTATION_FOR_LIBCR_IPC_MUTEX_H YES
#include <libcr_ipc/mutex.h>

struct cr_mutex_waiter {
	cid_t                    cid;
};
SLIST_DECLARE_NODE(_cr_mutex_waiter_list, struct cr_mutex_waiter);

void cr_mutex_lock(cr_mutex_t *mu) {
	assert(mu);
	cr_assert_in_coroutine();

	if (!mu->locked) /* non-blocking fast-path */
		mu->locked = true;
	else { /* blocking slow-path */
		struct _cr_mutex_waiter_list_node self = { .val = {
			.cid     = cr_getcid(),
		}};
		slist_push_to_rear(&mu->waiters, &self);
		cr_pause_and_yield();
	}
	assert(mu->locked);
}

void cr_mutex_unlock(cr_mutex_t *mu) {
	assert(mu);
	cr_assert_in_coroutine();

	assert(mu->locked);
	if (mu->waiters.front) {
		cr_unpause(mu->waiters.front->val.cid);
		slist_pop_from_front(&mu->waiters);
	} else
		mu->locked = false;
}