summaryrefslogtreecommitdiff
path: root/lib/thread/condvar+linux.myr
blob: 072e450827645f694fe13cc471c9dd6ce12dedbb (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
use std
use sys

use "atomic.use"
use "mutex.use"

pkg thread =
	type cond = struct
		_mtx	: mutex#
		_seq	: int32
	;;

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

generic Zptr = 0 castto(@a#)
const Zmtx = 0 castto(mutex#)

const mkcond = {
	-> [._mtx = Zmtx, ._seq = 0]
}

const condwait = {cond, mtx
	var seq

	seq = cond._seq
	if cond._mtx != mtx
		if cond._mtx != Zmtx
			std.die("multiple mutexes used with cond var")
		;;
		mtxcas(&cond._mtx, Zmtx, mtx)
		if cond._mtx != Zmtx
			std.die("multiple mutexes used with cond var")
		;;
	;;
	mtxunlock(cond._mtx)
	sys.futex(&cond._seq, sys.Futexwait | sys.Futexpriv, seq, Zptr, Zptr, 0)

	while xchg(&mtx._state, Contended) != Unlocked
		sys.futex(&mtx._state, sys.Futexwait | sys.Futexpriv, Contended, Zptr, Zptr, 0)
	;;
}

const condsig = {cond : cond#
	xadd(&cond._seq, 1)
	sys.futex(&cond._seq, sys.Futexwake | sys.Futexpriv, 1, Zptr, Zptr, 0)
}

const condbroadcast = {cond : cond#
	var m

	m = cond._mtx
	if m != Zmtx
		xadd(&cond._seq, 1)
		sys.futex(&cond._seq, sys.Futexrequeue | sys.Futexpriv, 1, Zptr, &m._state, 0)
	;;
}

const mtxcas = {mtxp, old, new
	-> xcas(mtxp castto(std.intptr#), \
		old castto(std.intptr), \
		new castto(std.intptr)) castto(mutex#)
}