mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
doc: describe coroutines and how to exchange data
This commit is contained in:
parent
8fe70a24a8
commit
288ea182a8
37
doc/docs.md
37
doc/docs.md
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user