summaryrefslogtreecommitdiff
path: root/lib/thread/condvar.myr
blob: 4fde70731666325005dd1a175d6807b4e779cd52 (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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use std

use "atomic"
use "common"
use "mutex"
use "sem"

pkg thread =
	type cond = struct
		_mtx	: mutex#
		_waitq	: condwaiter#
		_lock	: mutex
	;;

	const mkcond	: (mtx : mutex# -> cond)
	const condwait	: (cond : cond# -> void)
	const condsignal	: (cond : cond# -> void)
	const condbroadcast	: (cond : cond# -> void)
;;

/*
The waitqueue is a doubly-linked list because we'll need to remove waiters from
anywhere in the list when we add timeout support.

`cond._waitq.prev` is the tail of the queue.
*/
type condwaiter = struct
	next : condwaiter#
	prev : condwaiter#
	sem : sem
;;

const mkcond = {mtx
	-> [._mtx = mtx, ._lock = mkmtx()]
}

const condwait = {cond
	var mtx = cond._mtx
	var lock = &cond._lock
	var waiter = std.mk([.sem = mksem(0)])

	mtxlock(lock)
	match cond._waitq
	| Zptr:
		waiter.prev = waiter
		cond._waitq = waiter
	| q:
		waiter.prev = q.prev
		waiter.prev.next = waiter
		q.prev = waiter
	;;

	mtxunlock(lock)
	mtxunlock(mtx)
	semwait(&waiter.sem)
	std.free(waiter)
	mtxlock(mtx)
}

const condsignal = {cond
	var lock = &cond._lock

	mtxlock(lock)
	var head = cond._waitq
	if head != Zptr
		if head.next != Zptr
			head.next.prev = head.prev
		;;
		cond._waitq = head.next
		sempost(&head.sem)
	;;
	mtxunlock(lock)
}

/*
Yes, this invites the thundering herd but that's what you get for not
supporting futexes at all.
*/
const condbroadcast = {cond
	var lock = &cond._lock
	var head = Zptr

	mtxlock(lock)
	while (head = cond._waitq) != Zptr
		cond._waitq = head.next
		sempost(&head.sem)
	;;
	mtxunlock(lock)
}