v2 / vlib / x / atomics / examples / spinlock.v
59 lines · 45 sloc · 977 bytes · edd4a7129fa45c0bb5d5923b5b1a64cb5053ce46
Raw
1module main
2
3import x.atomics
4
5struct SpinLock {
6mut:
7 state u32 // 0 = unlocked, 1 = locked
8}
9
10fn acquire(mut spinlock SpinLock) {
11 for !atomics.cas_u32(&spinlock.state, 0, 1) {
12 // Busy-wait
13 }
14}
15
16fn release(mut spinlock SpinLock) {
17 atomics.store_u32(&spinlock.state, 0)
18}
19
20struct SharedData {
21mut:
22 spinlock SpinLock
23 value int
24}
25
26fn worker(mut data SharedData, iterations int) {
27 for _ in 0 .. iterations {
28 acquire(mut data.spinlock)
29 data.value++
30 release(mut data.spinlock)
31 }
32}
33
34fn main() {
35 mut data := &SharedData{}
36
37 num_threads := 4
38 iterations_per_thread := 10000
39
40 mut threads := []thread{}
41
42 for _ in 0 .. num_threads {
43 threads << spawn worker(mut data, iterations_per_thread)
44 }
45
46 threads.wait()
47
48 expected := num_threads * iterations_per_thread
49 actual := data.value
50
51 println('Expected: ${expected}')
52 println('Actual: ${actual}')
53
54 if actual == expected {
55 println('Spinlock works correctly')
56 } else {
57 println('Race condition detected')
58 }
59}
60