/
mutexes.ooc
75 lines (57 loc) · 1.23 KB
/
mutexes.ooc
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
67
68
69
70
71
72
73
74
import threading/Thread, os/Time, structs/ArrayList
// woo, evil globals. but it's for the purpose of our demonstration so deal with it.
mutex := Mutex new()
value : Int
maxThreads := const 100
iterations := const 5000
// our entry point
main: func {
// test without synchronization first
value = 0
unsafeTest()
printf("unsafe value = %d\n", value)
// and now with synchronization
value = 0
safeTest()
printf(" safe value = %d\n", value)
// destroy our mutex
mutex destroy()
}
unsafeTest: func {
value = 0
c := func {
for(i in 0..iterations) {
incrementUnsafe()
}
}
list := ArrayList<Thread> new()
for(i in 0..maxThreads) {
list add(Thread new(c). start())
}
for(t in list) {
t wait()
}
}
safeTest: func {
value = 0
c := func {
for(i in 0..iterations) {
incrementSafe()
}
}
list := ArrayList<Thread> new()
for(i in 0..maxThreads) {
list add(Thread new(c). start())
}
for(t in list) {
t wait()
}
}
incrementUnsafe: func {
value += 1
}
incrementSafe: func {
mutex lock()
value += 1
mutex unlock()
}