summaryrefslogtreecommitdiff
path: root/lib/thread/sem+futex.myr
blob: d79bd41b709ea039212c13cb333cc99c1dbb3a3a (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
use std

use "atomic"
use "common"
use "futex"

pkg thread =
	type sem = struct
		_val : ftxtag
	;;

	const mksem : (v : uint32 -> sem)
	const semwait : (s : sem# -> void)
	const semtrywait : (s : sem# -> bool)
	const sempost : (s : sem# -> void)
;;

const mksem = {v
	-> [._val = (v : ftxtag)]
}

const semwait = {s
	var v = 0

	for ; ;
		while (v = s._val) > 0
			if xcas(&s._val, v, v - 1) == v
				-> void
			;;
		;;
		ftxwait(&s._val, v, Zptr)
	;;
}

const semtrywait = {s
	for ; ;
		var v = xget(&s._val)
		if v == 0
			-> false
		;;
		if xcas(&s._val, v, v - 1) == v
			-> true
		;;
	;;
	-> false /* Unreachable */
}

const sempost = {s
	std.assert((xadd(&s._val, 1) : uint32) != ~0x0, "error: semaphore overflowed\n")

	/* Unconditionally wake one waiter */
	ftxwake(&s._val)
}