doc: describe coroutines and how to exchange data

pull/5524/head
Uwe Krüger 2020-06-26 23:55:34 +02:00 committed by GitHub
parent 8fe70a24a8
commit 288ea182a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 37 additions and 0 deletions

View File

@ -1348,6 +1348,43 @@ 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.
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:
```v
import sync
struct St {
mut:
x int // share data
mtx &sync.Mutex
}
fn (mut b St) g() {
...
b.mtx.lock()
// read/modify/write b.x
...
b.mtx.unlock()
...
}
fn caller() {
mut a := &St{ // create as reference so it's on the heap
x: 10
mtx: sync.new_mutex()
}
go a.g()
...
a.mtx.lock()
// read/modify/write a.x
...
a.mtx.unlock()
...
}
```
## Decoding JSON
```v