summaryrefslogtreecommitdiff
path: root/lib/thread/condvar.myr
blob: f843f843ae88a979a411a668896db731ae7def95 (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
use std

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

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

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

type condwaiter = struct
	next : 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._tail
	| Zptr: cond._head = cond._tail = waiter
	| tail: cond._tail = tail.next = 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._head
	if head != Zptr
		cond._head = head.next
		sempost(&head.sem)
		if cond._head == Zptr
			cond._tail = Zptr
		;;
	;;
	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._head) != Zptr
		cond._head = head.next
		sempost(&head.sem)
	;;
	cond._tail = Zptr
	mtxunlock(lock)
}