| 1 | module main |
| 2 | |
| 3 | import x.atomics |
| 4 | |
| 5 | fn increment(counter &i64) { |
| 6 | atomics.add_i64(counter, 1) |
| 7 | } |
| 8 | |
| 9 | fn worker(counter &i64, iterations int) { |
| 10 | for _ in 0 .. iterations { |
| 11 | increment(counter) |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | fn main() { |
| 16 | mut counter := i64(0) |
| 17 | |
| 18 | num_threads := 4 |
| 19 | increments_per_thread := 10000 |
| 20 | |
| 21 | mut threads := []thread{} |
| 22 | |
| 23 | for _ in 0 .. num_threads { |
| 24 | threads << spawn worker(&counter, increments_per_thread) |
| 25 | } |
| 26 | |
| 27 | threads.wait() |
| 28 | |
| 29 | expected := i64(num_threads * increments_per_thread) |
| 30 | actual := atomics.load_i64(&counter) |
| 31 | |
| 32 | println('Expected: ${expected}') |
| 33 | println('Actual: ${actual}') |
| 34 | |
| 35 | if actual == expected { |
| 36 | println('Counter is correct') |
| 37 | } else { |
| 38 | println('Counter mismatch - race condition detected') |
| 39 | } |
| 40 | } |
| 41 | |