| 1 | /* |
| 2 | This example demonstrates thread safety using V's concurrency features. |
| 3 | Key points: |
| 4 | - The `SharedData` struct contains a mutable counter that will be accessed by multiple threads. |
| 5 | - The `increment` function increments the counter within a lock to ensure that only one thread |
| 6 | can modify the counter at a time, preventing race conditions. |
| 7 | - In the `main` function, two threads are spawned to increment the shared counter concurrently. |
| 8 | - The `lock` keyword is used to ensure exclusive access to the shared data during modification, |
| 9 | and the `rlock` keyword is used to allow multiple threads to read the data concurrently without |
| 10 | modification. |
| 11 | This ensures that the counter is incremented safely and the final value is printed correctly. |
| 12 | */ |
| 13 | |
| 14 | struct SharedData { |
| 15 | mut: |
| 16 | counter int |
| 17 | } |
| 18 | |
| 19 | fn increment(shared data SharedData) { |
| 20 | lock data { |
| 21 | data.counter++ |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | fn main() { |
| 26 | shared data := SharedData{} |
| 27 | threads := [spawn increment(shared data), spawn increment(shared data)] |
| 28 | |
| 29 | for t in threads { |
| 30 | t.wait() // Wait for both threads to complete |
| 31 | } |
| 32 | |
| 33 | rlock data { |
| 34 | println('Counter: ${data.counter}') |
| 35 | } |
| 36 | } |
| 37 | |