summaryrefslogtreecommitdiff
path: root/lib/thread/sem+futex.myr
blob: 45bca0d9454a91dc12efcd64d70239b4e2acb46e (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 "atomic"
use "futex"

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

	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

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

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")

	if xget(&s._nwaiters) > 0
		ftxwake(&s._val)
	;;
}