summaryrefslogtreecommitdiff
path: root/lib/thread/sem+plan9.myr
blob: 221a8056c6fed85e2ddb8b55b6381030bbb24d63 (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
use std
use sys

use "atomic"
use "common"

pkg thread =
	type sem = struct
		_user : int32
		_kern : int32
	;;

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

const mksem = {v
	std.assert((v : int32) >= 0, "error: invalid initial semaphore value\n")
	-> [._user = (v : int32), ._kern = 0]
}

const semwait = {s
	var u = xadd(&s._user, -1)
	std.assert(u != ~0, "error: semaphore underflowed\n")

	/* When the userspace value is negative we fall back on the kernel semaphore */
	if u <= 0
		while sys.semacquire(&s._kern , 1) < 0
			/* Interrupted, retry */
		;;
	;;
}

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

const sempost = {s
	var u = xadd(&s._user, 1)
	std.assert(u != 0x7fffffff, "error: semaphore overflowed\n")
	if u < 0
		sys.semrelease(&s._kern, 1)
	;;
}