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

use "atomic"

pkg thread =
	type sem = struct
		_val : 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]
}

const semwait = {s
	var v = 0

	for var i = 0; i < 1000; i++
		if (v = xget(&s._val)) != 0 && xcas(&s._val, v, v - 1) == v
			-> void
		;;
	;;

	for var i = 0; i < 1000; i++
		if (v = xget(&s._val)) != 0 && xcas(&s._val, v, v - 1) == v
			-> void
		;;
		std.nanosleep(10_000)
	;;

	for var i = 0; i < 1000; i++
		if (v = xget(&s._val)) != 0 && xcas(&s._val, v, v - 1) == v
			-> void
		;;
		std.nanosleep(100_000)
	;;

	for ; ;
		if (v = xget(&s._val)) != 0 && xcas(&s._val, v, v - 1) == v
			-> void
		;;
		std.nanosleep(1_000_000)
	;;
}

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) != ~0x0, "error: semaphore overflowed\n")
}