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

#include <assert.h>

#include <libcr_ipc/mutex.h>

void cr_mutex_lock(cr_mutex_t *mu) {
	assert(mu);
	if (!mu->tail)
		mu->tail = &mu->head;
	if (!mu->locked) {
		mu->locked = true;
		return;
	}
	struct _cr_ipc_cid_list self = {
		.val = cr_getcid(),
		.next = NULL,
	};
	*(mu->tail) = &self;
	mu->tail = &(self.next);
	cr_pause_and_yield();
}

void cr_mutex_unlock(cr_mutex_t *mu) {
	assert(mu);
	assert(mu->tail);
	assert(mu->locked);
	if (mu->head) {
		cr_unpause(mu->head->val);
		mu->head = mu->head->next;
		if (!mu->head)
			mu->tail = &mu->head;
	} else
		mu->locked = false;
}