v / examples / thread_safety / concurrent_shared_data.v
36 lines · 31 sloc · 1.07 KB · 5ec9bb54b80bfde832e5fbfe78cd282b2ccac759
Raw
1/*
2This example demonstrates thread safety using V's concurrency features.
3Key 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
6can 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,
9and the `rlock` keyword is used to allow multiple threads to read the data concurrently without
10modification.
11This ensures that the counter is incremented safely and the final value is printed correctly.
12*/
13
14struct SharedData {
15mut:
16 counter int
17}
18
19fn increment(shared data SharedData) {
20 lock data {
21 data.counter++
22 }
23}
24
25fn 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