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

use "atomic"

pkg thread =
	type mutex = struct
		_state	: uint32
	;;	

	const mkmtx	: (-> mutex)
	const mtxlock	: (mtx : mutex# -> void)
	const mtxtrylock	: (mtx : mutex# -> bool)
	const mtxunlock	: (mtx : mutex# -> void)
;;

const mkmtx = {
	-> [._state = 0]
}

/* a shitty spinlock */
const mtxlock = {mtx
	/* first fast */
	for var i = 0; i < 1000; i++
		if xcas(&mtx._state, 0, 1) == 0
			-> void
		;;
		std.nanosleep(0)
	;;
	
	/* then slower */
	for var i = 0; i < 1000; i++
		if xcas(&mtx._state, 0, 1) == 0
			-> void
		;;
		std.nanosleep(10_000) /* 10 us */
	;;

	/* even slower */
	for var i = 0; i < 1000; i++
		if xcas(&mtx._state, 0, 1) == 0
			-> void
		;;
		std.nanosleep(100_000) /* 100 us */
	;;

	/* I'm rip van winkle! */
	while true
		if xcas(&mtx._state, 0, 1) == 0
			-> void
		;;
		std.nanosleep(1000_000) /* 1 ms */
	;;
}

const mtxtrylock = {mtx
	-> xcas(&mtx._state, 0, 1) == 0
}

	
const mtxunlock = {mtx
	xset(&mtx._state, 0)
}