summaryrefslogtreecommitdiff
path: root/lib/thread/condvar+openbsd:6.2.myr
blob: 29dbb35fad05b35e669a453f9a9f8ca7f2c99c2f (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
use std
use sys

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

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

	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 seq : uint32
	var mtx

	mtx = cond._mtx
	seq = cond._seq
	mtxunlock(mtx)

	/*
	FIXME?: `futex` can be interrupted but `condwait` should always be done
	in a loop anyway.
	*/
	sys.futex(&cond._seq, sys.Futexwait, (seq : int), Zptr, Zptr)

	/*
	We need to atomically set the mutex to contended. This allows us to
	pass responsibility for waking up the potential other waiters on to the
	unlocker of the mutex.
	*/
	mtxcontended(mtx)
}

const condsignal = {cond : cond#
	xadd(&cond._seq, 1)
	sys.futex(&cond._seq, sys.Futexwake, 1, Zptr, Zptr)
}

const condbroadcast = {cond : cond#
	xadd(&cond._seq, 1)
	sys.futex(&cond._seq, sys.Futexrequeue, 1,
		(0x7fffffff : sys.timespec#),
		(&cond._mtx._state : uint32#))
}