doc: concurency example with WaitGroup (#6034)
parent
d71c11577a
commit
4b8652755d
30
doc/docs.md
30
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
|
call it with `go foo()`. Right now, it launches the function on a new system
|
||||||
thread. Soon coroutines and a scheduler will be implemented.
|
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
|
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
|
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:
|
the coroutine as `mut`. The underlying `struct` should also contain a `mutex` to lock concurrent access:
|
||||||
|
|
Loading…
Reference in New Issue