Concurrency
The concurrency model in V was heavily inspired by Go. An important difference at the moment is the fact that there are no coroutines in V, so any functions run in a separate system thread, which reduces flexibility.
Coroutines are planned, but they are not implemented at the moment.
Spawning Concurrent Tasks
To run a function on a separate thread, use the spawn
keyword:
You can also use anonymous functions:
V also has the go
keyword, it is reserved for coroutines, currently it works the same as spawn
and will be automatically changed to spawn
when formatted with vfmt
.
Waiting for a function to finish
To wait for the completion of a function running in a separate thread, the result of
the spawn
expression can be assigned to a variable that will act as handle.
This handle can be used to wait for the function to complete by calling the wait()
method:
Using this approach, you can also get the return value from a function running on a separate thread.
This will not require changing the signature of the function itself.
Threads array
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.
main()
Spawning Threads in Consider the following code:
Here we are running the watcher()
function in a separate thread, however the problem is
that main()
will finish before watcher()
has started, so the program will exit even
though watcher()
has not finished yet.
To avoid this, use the wait()
described in the
previous section:
Change Stack Size
To change the stack size of a thread, use the spawn_stack
attribute:
Thread Communication
V uses channels to communicate between threads, they will be discussed in the next article.