v / examples / thread_safety / atomic_counter.v
44 lines · 34 sloc · 1.83 KB · 7a0febb12dad9fa4711bfcff68b71dfc0003dca1
Raw
1/*
2This code demonstrates thread safety using atomic operations in V.
3
4Thread safety is achieved by using atomic functions to manipulate the shared counter variable.
5Atomic operations ensure that the read-modify-write sequence is performed as a single, indivisible operation,
6preventing race conditions and ensuring data integrity when accessed by multiple threads concurrently.
7
8Key points:
91. **Atomic Fetch and Add**: The `C.atomic_fetch_add_u32` function atomically increments the counter.
10 This means that the increment operation is performed without interruption, ensuring that no two threads
11 can increment the counter simultaneously and cause a race condition.
12
132. **Atomic Load**: The `C.atomic_load_u32` function atomically reads the value of the counter.
14 This ensures that the read operation is consistent and not affected by concurrent writes from other threads.
15
163. **Thread Synchronization**: The `spawn` function is used to create new threads that run the `increment` function.
17 The `wait` method is called on each thread to ensure that the main thread waits for both threads to complete
18 before reading the final value of the counter.
19
20By using atomic operations and proper thread synchronization, the code ensures that the shared counter is
21incremented safely and correctly by multiple threads.
22*/
23import sync as _
24
25// Function to increment the atomic counter
26fn increment(atomic_counter &u32) {
27 C.atomic_fetch_add_u32(atomic_counter, 1)
28}
29
30fn main() {
31 atomic_counter := u32(0) // Atomic counter variable
32
33 // Spawn two threads that increment the atomic counter
34 t1 := spawn increment(&atomic_counter)
35 t2 := spawn increment(&atomic_counter)
36
37 // Wait for both threads to complete
38 t1.wait()
39 t2.wait()
40
41 // Load and print the final value of the atomic counter
42 final_count := C.atomic_load_u32(&atomic_counter)
43 println('Atomic Counter: ${final_count}')
44}
45