Concurrency
Spawning Concurrent Tasks
V's model of concurrency is similar to Go's.
go foo() runs foo() concurrently in a lightweight thread managed by the V runtime.
spawn foo() runs foo() concurrently in a different thread:
[!NOTE] Threads rely on the machine's CPU (number of cores/threads). Be aware that OS threads spawned with
spawnhave limitations in regard to concurrency, including resource overhead and scalability issues, and might affect performance in cases of high thread count.
Sometimes it is necessary to wait until a parallel thread has finished. This can
be done by assigning a handle to the started thread and calling the wait() method
to this handle later:
This approach can also be used to get a return value from a function that is run in a parallel thread. There is no need to modify the function itself to be able to call it concurrently.
If there is a large number of tasks, it might be easier to manage them using an array of threads.
Additionally for threads that return the same type, calling wait()
on the thread array will return all computed values.
Channels
Channels are the preferred way to communicate between threads. They allow threads to exchange data
safely without requiring explicit locking. V's channels are similar to those in Go, enabling you
to push objects into a channel on one end and pop objects from the other.
Channels can be buffered or unbuffered, and you can use the select statement to monitor multiple
channels simultaneously.
Syntax and Usage
Channels are declared with the type chan objtype.
You can optionally specify a buffer length using the cap field:
Channels do not have to be declared as mut. The buffer length is not part of the type but
a field of the individual channel object. Channels can be passed to threads like normal
variables:
Buffered Channels
Buffered channels allow you to push multiple items without blocking, as long as the buffer is not full:
Closing Channels
A channel can be closed to indicate that no further objects can be pushed. Any attempt
to do so will then result in a runtime panic (with the exception of select and
try_push() - see below). Attempts to pop will return immediately if the
associated channel has been closed and the buffer is empty. This situation can be
handled using an or {} block (see Handling options/results).
Note: buffered channels can be closed while they have unread values in them. The buffered values can be retrieved, even after the closing:
... will produce:
>> loop 0..2 | x: 0 | ich.closed: false
>> loop 0..2 | x: 1 | ich.closed: false
>> final loop | x: 2 | ich.closed: true
>> final loop | x: 3 | ich.closed: true
>> final loop | x: 4 | ich.closed: true
Note: reading from the .closed field of the channel in the example,
is done just for clarity of illustration. The recommended way to pop values
from the channel is with: x := <-ich or { break } in a for loop,
which will cleanly break out of the loop, when the channel is closed and empty.
Avoid manually checking, whether the channel was closed or not, because that
can introduce data races, if you are not careful.
Channel Select
The select command allows monitoring several channels at the same time
without noticeable CPU load. It consists of a list of possible transfers and associated branches
of statements - similar to the match command:
The timeout branch is optional. If it is absent select waits for an unlimited amount of time.
It is also possible to proceed immediately if no channel is ready in the moment select is called
by adding an else { ... } branch. else and <timeout> are mutually exclusive.
The select command can be used as an expression of type bool
that becomes false if all channels are closed:
Special Channel Features
For special purposes there are some builtin fields and methods:
The try_push/pop() methods will return immediately with one of the results
.success, .not_ready or .closed - dependent on whether the object has been transferred or
the reason why not.
Usage of these methods and fields in production is not recommended -
algorithms based on them are often subject to race conditions. Especially .len and
.closed should not be used to make decisions.
Use or branches, error propagation or select instead (see Syntax and Usage
and Channel Select above).
Shared Objects
Data can be exchanged between a thread and the calling thread via a shared variable.
Such variables should be created as shared and passed to the thread as such, too.
The underlying struct contains a hidden mutex that allows locking concurrent access
using rlock for read-only and lock for read/write access.
Note: Shared variables must be structs, arrays or maps.
Example of Shared Objects
Difference Between Channels and Shared Objects
Purpose:
- Channels: Used for message passing between threads, ensuring safe communication.
- Shared objects: Used for direct data sharing and modification between threads.
Synchronization:
- Channels: Implicit (via channel operations)
- Shared objects: Explicit (via
rlock/lockblocks)