1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

doc: concurency example with WaitGroup (#6034)

This commit is contained in:
Maciej Obarski 2020-08-01 23:08:57 +02:00 committed by GitHub
parent d71c11577a
commit 4b8652755d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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: