blob: e2e1207fa381f1b9c9efe22db2c408123c899814 (
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
|
use std
use sys
use "atomic"
use "common"
pkg thread =
type mutex = struct
_state : int32
_sem : int32
;;
const mkmtx : (-> mutex)
const mtxlock : (mtx : mutex# -> void)
const mtxtrylock : (mtx : mutex# -> bool)
const mtxunlock : (mtx : mutex# -> void)
;;
const mkmtx = {
-> [._state = 0, ._sem=0]
}
const mtxlock = {mtx
/* if the old value was 0, we aren't contended */
if xadd(&mtx._state, 1) == 0
-> void
;;
while sys.semacquire(&mtx._sem, 1) < 0
/* interrupted; retry */
;;
}
const mtxtrylock = {mtx
-> xcas(&mtx._state, 0, 1) == 0
}
const mtxunlock = {mtx
/* if we were the only thread waiting on the lock, there was no contention */
if xadd(&mtx._state, -1) == 1
-> void
;;
sys.semrelease(&mtx._sem, 1)
}
|