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

use "atomic"
use "mutex"
use "futex"

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

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

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

const condwait = {cond
	var mtx = cond._mtx
	var seq = xget(&cond._seq)

	mtxunlock(mtx)
	ftxwait(&cond._seq, seq, -1)

	/*
	In the event of a broadcast, we aren't requeueing waiters from the
	condvar's futex to the mutex's futex so we can just reacquire the mutex
	normally.
	*/
	mtxlock(mtx)
}

const condsignal = {cond : cond#
	xadd(&cond._seq, 1)
	ftxwake(&cond._seq)
}

/*
`umtx_op` fully supports implementing condvars efficiently but also requires
condvars to be implemented in a specific way. For now we'll just invite the
thundering herd.
*/
const condbroadcast = {cond : cond#
	xadd(&cond._seq, 1)
	ftxwakeall(&cond._seq)
}