| 1 | module main |
| 2 | |
| 3 | import x.atomics |
| 4 | |
| 5 | struct SpinLock { |
| 6 | mut: |
| 7 | state u32 // 0 = unlocked, 1 = locked |
| 8 | } |
| 9 | |
| 10 | fn acquire(mut spinlock SpinLock) { |
| 11 | for !atomics.cas_u32(&spinlock.state, 0, 1) { |
| 12 | // Busy-wait |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | fn release(mut spinlock SpinLock) { |
| 17 | atomics.store_u32(&spinlock.state, 0) |
| 18 | } |
| 19 | |
| 20 | struct SharedData { |
| 21 | mut: |
| 22 | spinlock SpinLock |
| 23 | value int |
| 24 | } |
| 25 | |
| 26 | fn 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 | |
| 34 | fn 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 | |