From 4b8652755d1a78bef669d1e5ebe99afbb2c727c1 Mon Sep 17 00:00:00 2001 From: Maciej Obarski Date: Sat, 1 Aug 2020 23:08:57 +0200 Subject: [PATCH] doc: concurency example with WaitGroup (#6034) --- doc/docs.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/doc/docs.md b/doc/docs.md index 6e3b978345..8ac9ff5b21 100644 --- a/doc/docs.md +++ b/doc/docs.md @@ -1683,6 +1683,36 @@ V's model of concurrency is very similar to Go's. To run `foo()` concurrently, j call it with `go foo()`. Right now, it launches the function on a new system thread. Soon coroutines and a scheduler will be implemented. +```v +import sync +import time + +fn task(id, duration int, mut wg sync.WaitGroup) { + println("task ${id} begin") + time.sleep_ms(duration) + println("task ${id} end") + wg.done() +} + +fn main() { + mut wg := sync.new_waitgroup() + wg.add(3) + go task(1, 500, mut wg) + go task(2, 900, mut wg) + go task(3, 100, mut wg) + wg.wait() + println('done') +} + +// Output: task 1 begin +// task 2 begin +// task 3 begin +// task 3 end +// task 1 end +// task 2 end +// done +``` + Unlike Go, V has no channels (yet). Nevertheless, data can be exchanged between a coroutine and the calling thread via a shared variable. This variable should be created as reference and passed to the coroutine as `mut`. The underlying `struct` should also contain a `mutex` to lock concurrent access: