diff --git a/examples/thread_safety/atomic_counter.v b/examples/thread_safety/atomic_counter.v index b6379e2d3b..6abbeffc5b 100644 --- a/examples/thread_safety/atomic_counter.v +++ b/examples/thread_safety/atomic_counter.v @@ -20,15 +20,7 @@ Key points: By using atomic operations and proper thread synchronization, the code ensures that the shared counter is incremented safely and correctly by multiple threads. */ -$if windows { - #include "@VEXEROOT/thirdparty/stdatomic/win/atomic.h" -} $else { - #include "@VEXEROOT/thirdparty/stdatomic/nix/atomic.h" -} - -// Declare the atomic functions -fn C.atomic_fetch_add_u32(&u32, u32) u32 -fn C.atomic_load_u32(&u32) u32 +import sync as _ // Function to increment the atomic counter fn increment(atomic_counter &u32) { diff --git a/examples/thread_safety/queue.v b/examples/thread_safety/queue.v index 6228ee5562..2dbcc2ddc4 100644 --- a/examples/thread_safety/queue.v +++ b/examples/thread_safety/queue.v @@ -1,49 +1,94 @@ /* -This example demonstrates thread safety using channels in V. +This example demonstrates thread safety using a queue of callbacks. ### Functions: -- `producer(ch chan int)`: This function simulates a producer that sends integers from 1 to 99 to -the channel `ch`. It prints each produced item. -- `consumer(ch chan int)`: This function simulates a consumer that receives integers from the -channel `ch`. +- `producer`: creates a callback and adds it to the queue. +- `consumer`: consumes a callback from the queue and runs it. +- `heavy_processing`: a heavy processing function that is added to the queue. ### Thread Safety: -- The use of channels ensures thread safety by providing a synchronized way to communicate between -the producer and consumer threads. -- Channels in V are designed to handle concurrent access, preventing race conditions and ensuring -that data is safely passed between threads. -- The `select` statement in the consumer function allows it to handle timeouts gracefully, -ensuring that the program does not hang if the producer is not ready. +- The `fn producer` function is protected by a mutex. It locks the mutex before adding a callback +to the queue and unlocks it after adding the callback. +- The `fn consumer` function is also protected by the same mutex. It locks the mutex before +consuming a callback from the queue and unlocks it after consuming the callback. +- The `heavy_processing` function is added to the queue by the main thread before the producer +threads start producing callbacks. The main thread is the only thread that adds this function to +the queue, so it doesn't need to be protected by a mutex. */ import time +import sync -fn producer(ch chan int) { - for i in 1 .. 100 { - ch <- i +type Callback = fn (id string) + +fn producer(producer_name string, mut arr []Callback, mut mtx sync.Mutex) { + for i in 1 .. 5 { + mtx.lock() + arr << fn [producer_name, i] (consumer_name string) { + println('task ${i} created by producer ${producer_name}: consumed by ${consumer_name}') + time.sleep(500 * time.millisecond) + } println('Produced: ${i}') + time.sleep(50 * time.millisecond) + mtx.unlock() } } -fn consumer(ch chan int) { +fn consumer(consumer_name string, mut arr []Callback, mut mtx sync.Mutex) { for { - select { - item := <-ch { - println('Consumed: ${item}') - } - 500 * time.millisecond { - println('Timeout: No producers were ready within 0.5s') - break - } + mtx.lock() + if arr.len > 0 { + callback := arr[0] + arr.delete(0) + + mtx.unlock() + callback(consumer_name) // run after unlocking to allow other threads to consume + continue + } else { + println('- No items to consume') + mtx.unlock() + + // time.sleep(500 * time.millisecond) + // continue // uncomment to run forever + + break // uncomment to stop after consuming all items } } } -fn main() { - ch := chan int{cap: 10} - - producer_thread := spawn producer(ch) - consumer_thread := spawn consumer(ch) - - producer_thread.wait() - consumer_thread.wait() +fn heavy_processing(queue_id string) { + println('One more: ${queue_id}') + time.sleep(500 * time.millisecond) +} + +fn main() { + mut mtx := sync.new_mutex() + mut arr := []Callback{} + + producer_threads := [ + spawn producer('Paula', mut &arr, mut mtx), + spawn producer('Adriano', mut &arr, mut mtx), + spawn producer('Kaka', mut &arr, mut mtx), + spawn producer('Hitalo', mut &arr, mut mtx), + spawn producer('Jonh', mut &arr, mut mtx), + ] + + mut consumer_threads := [ + spawn consumer('consumer number 0', mut &arr, mut mtx), + ] + + // spawn 16 consumers + for i in 1 .. 16 { + consumer_threads << spawn consumer('consumer number ${i}', mut &arr, mut mtx) + } + + mtx.lock() + arr << heavy_processing + mtx.unlock() + + for t in producer_threads { + t.wait() + } + for t in consumer_threads { + t.wait() + } } diff --git a/examples/thread_safety/readme.md b/examples/thread_safety/readme.md index 9c4e2b4e83..97f939a2cc 100644 --- a/examples/thread_safety/readme.md +++ b/examples/thread_safety/readme.md @@ -1,17 +1,16 @@ ### Run ```sh -v -prod -autofree ./queue.v -o ./queue.c && \ -gcc ./queue.c -o ./queue.out && \ -./queue.out +v -prod -gc none -cc gcc ./queue.v && \ +./queue ``` ### Valgrind ```sh # Helgrind: a tool for detecting synchronisation errors in programs that use the POSIX pthreads threading primitives. -valgrind --tool=helgrind ./queue.out +valgrind --tool=helgrind ./queue # DRD: a tool for detecting errors in multithreaded programs. The tool works for any program that uses the POSIX threading primitives or that uses threading concepts built on top of the POSIX threading primitives. -valgrind --tool=drd ./queue.out +valgrind --tool=drd ./queue ```