Skip to content

Running tasks at the same time

A task is a function that runs at the same time as other tasks. While one task waits for a file, the network or a timer, the other tasks keep working. You write ordinary code. A call that waits, like Core\Time::sleep, returns when it is done.

A function that waits

Novis has no async, no await on a promise, no Fiber and no callback style. A function that waits is an ordinary function. When it reads a file, sleeps or takes a value from a channel, it stops the task that called it and returns when the answer is there. The result is the value itself, with nothing to unwrap, and the lines around the call run in their own order.

The same function works when you call it on its own line and when you call it inside a group of tasks.

You get concurrency by running several tasks, not by marking functions. While one task waits, another runs. A task belongs to the call that started it, and that call does not return while any of its tasks is still running.

The examples below show an ordinary function that waits, two tasks taking turns, and a page that asks for two slow answers at once.

A function that waits is an ordinary function

<?nvs
// Shows that waiting needs no special syntax. `Core\Time::sleep` stops this task
// until the time has passed. The lines around it run one after another, in order.
class Report
{
public static function rows(): array<string>
{
// A real program reads a file or asks a database here. Both of those wait.
Core\Time::sleep(10ms);
return ['north', 'south'];
}
}
echo "asking for the rows\n";
// The result is the array itself. There is nothing to unwrap.
array<string> $rows = Report::rows();
echo 'got ', Core\Arr::count($rows), " rows\n";
foreach ($rows as string $row) {
echo $row, "\n";
}
Output
asking for the rows
got 2 rows
north
south

While one task waits another runs

<?nvs
// Shows what a wait does inside a group of tasks. `slow` waits 40 milliseconds and
// `quick` waits 5. While `slow` waits, `quick` runs and finishes first. The steps are
// kept in a variable, because a task collects what it prints until the group is done.
class Trace
{
public static string $steps = '';
public static function note(string $what): void
{
Trace::$steps = Trace::$steps . $what . "\n";
}
}
Core\Task::all({
slow: fn(): void => {
Trace::note('slow starts');
Core\Time::sleep(40ms);
Trace::note('slow is done');
},
quick: fn(): void => {
Trace::note('quick starts');
Core\Time::sleep(5ms);
Trace::note('quick is done');
},
});
// Both tasks start, and `quick` is done long before `slow`.
echo Trace::$steps;
Output
quick starts
slow starts
quick is done
slow is done

A page asks for two slow answers at once

<?nvs
// Shows a real use: a page needs a customer and their orders, and both answers come
// from somewhere slow. These are ordinary functions, so the page can ask for them at
// the same time or one at a time. The functions are written the same way either way.
class Store
{
public static function customer(): string
{
Core\Time::sleep(5ms);
return 'Ada Lovelace';
}
public static function orders(): array<string>
{
Core\Time::sleep(5ms);
return ['A-1001', 'A-1002'];
}
public static function banner(): string
{
Core\Time::sleep(5ms);
return 'Free delivery this week';
}
}
// Neither answer needs the other, so both are asked for at the same time.
var $page = Core\Task::all({
customer: Store::customer,
orders: Store::orders,
});
echo $page->customer, "\n";
foreach ($page->orders as string $order) {
echo 'order ', $order, "\n";
}
// The same kind of function, called on its own line.
string $banner = Store::banner();
echo $banner, "\n";
Output
Ada Lovelace
order A-1001
order A-1002
Free delivery this week

Details

async, await and Fiber are not keywords or classes. async function and await $x do not compile, and new Fiber(…) is E0303.

A task runs until it waits. Two tasks that never wait run one after the other, each from its first line to its last.

A task may start its own group of tasks. The inner Core\Task::all or Core\Task::map returns before the outer task goes on.

What a task prints with echo is kept until the group is done. Then each task's output is printed in the order the tasks were written, not in the order they finished. For Core\Task::map, that is the order of the array. The output of a task that was stopped or that threw is printed too.

A static property has one value, and every task of the program reads and writes that same value.

A fixed set of tasks

Core\Task::all runs a fixed set of jobs at the same time and gives you all their results together.

You give it a shape: a value with named fields, written { rows: …, label: … }. Each field holds a function that takes no arguments. Core\Task::all returns a shape with the same field names, and each field has the type that job's function returns. You read $page->rows straight away, with no conversion. A variable of type callable, with no signature, gives you mixed for that field alone.

Core\Task::all returns only when every job has finished, so nothing from the group is still running afterwards. The subject has to be a shape of functions. An array of functions does not compile.

The examples below show three jobs read by name, the three ways to write a job, a product page that loads its parts at the same time, and an array of functions that does not compile.

Three jobs read by name

<?nvs
// Shows how to run three jobs at the same time. `Core\Task::all` takes one field per
// job and returns one field per result, under the same names.
var $page = Core\Task::all({
rows: fn(): array<int> => [10, 20, 30],
label: fn(): string => 'orders',
total: fn(): int => 60,
});
// Each field already has the type its own function returns, so nothing needs converting.
// This prints orders: 3 rows, 60 in total.
echo $page->label, ': ', Core\Arr::count($page->rows), ' rows, ', $page->total, " in total\n";
Output
orders: 3 rows, 60 in total

The three ways to write a job

<?nvs
// Shows that where a job is written does not matter. A field can hold a function
// written in place, a method named with `(...)`, or a function kept in a variable.
class Stock
{
public static function onHand(): int
{
return 42;
}
}
var $kept = fn(): string => 'from a variable';
var $group = Core\Task::all({
here: fn(): string => 'written in place',
method: Stock::onHand,
kept: $kept,
});
// This prints written in place, then 42, then from a variable.
echo $group->here, "\n";
echo $group->method, "\n";
echo $group->kept, "\n";
Output
written in place
42
from a variable

A product page loads its parts at once

<?nvs
// Shows a real use: a product page needs three things before it can be drawn, and
// none of them needs the others. Running them together takes as long as the slowest
// one, instead of as long as all three added up.
class Catalog
{
public static function product(): string
{
return 'Espresso machine';
}
public static function stock(): int
{
return 12;
}
public static function reviews(): array<string>
{
return ['fast', 'quiet'];
}
}
var $page = Core\Task::all({
product: Catalog::product,
stock: Catalog::stock,
reviews: Catalog::reviews,
});
echo $page->product, "\n";
echo 'in stock: ', $page->stock, "\n";
foreach ($page->reviews as string $review) {
echo '- ', $review, "\n";
}
Output
Espresso machine
in stock: 12
- fast
- quiet

An array of functions does not compile

<?nvs
// Shows that `Core\Task::all` needs named fields. An array of functions has no
// names, so this program does not compile.
// proof: compile-error
var $results = Core\Task::all([fn(): int => 1, fn(): int => 2]);
Output
error[E0401]: expected `{ name: callable(): T, ... }`, found `array<mixed>`
--> 04-an-array-of-functions-does-not-compile.nvs:6:31
|
6 | var $results = Core\Task::all([fn(): int => 1, fn(): int => 2]);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ this is `array<mixed>`
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

The type of a field in the result is the return type of its function. For fn(): int => … it is int. A fn with an expression body and no return type gives the type of that expression. A variable of type callable, with no signature, gives mixed. A variable of type callable(): int gives int.

A field of type mixed converted with as string is a tainted string.

A function that returns void gives a void field. echo $r->a on it is E0707.

Reading a field that the shape does not have compiles and throws RuntimeError when it runs.

Core\Task::all({}) has no tasks and returns at once.

Each field must be a function. A field with another value, such as { a: 1 }, is E0401. An array of functions is E0401 too.

One task for each element

Core\Task::map calls one function once per element of an array, each call at the same time as the others, and gives you the results as an array.

The results come back under the input's own keys and in the input's own order. The order the jobs finished in does not change anything you see. The function receives the value and the key, in that order, and you may write only the value if the key is not needed. The result is an array of the type the function returns.

Core\Task::map returns only when every element has been handled, so nothing from the group is still running afterwards. If one job throws, the rest are stopped and the error reaches you at the call.

The examples below show one job per element, a function that reads the key as well, and an import that checks every row of a file at the same time.

One job for every element

<?nvs
// Shows how to run one job for every element of an array. `Core\Task::map` calls the
// function once per element, all at the same time, and returns the results as an array.
array<int> $prices = ['apple' => 3, 'pear' => 4, 'plum' => 5];
var $cents = Core\Task::map($prices, fn(int $euros): int => $euros * 100);
// The results keep the input's keys and the input's order.
// This prints apple=300, then pear=400, then plum=500.
foreach ($cents as string $fruit => int $amount) {
echo $fruit, '=', $amount, "\n";
}
Output
apple=300
pear=400
plum=500

The function can read the key too

<?nvs
// Shows the two parameters the function may take. The first is the element's value.
// The second is its key. You write the second one only when you need it.
array<int> $stock = ['Hamburg' => 12, 'Munchen' => 0, 'Koln' => 7];
// Only the value. This prints 24, 0 and 14.
var $doubled = Core\Task::map($stock, fn(int $count): int => $count * 2);
foreach ($doubled as int $count) {
echo $count, "\n";
}
// The value and the key. This prints Hamburg has 12, and so on for the other two.
var $lines = Core\Task::map($stock, fn(int $count, string $city): string => $city . ' has ' . $count);
foreach ($lines as string $line) {
echo $line, "\n";
}
Output
24
0
14
Hamburg has 12
Munchen has 0
Koln has 7

An import checks every row at once

<?nvs
// Shows a real use: an uploaded file has one order per row, and every row has to be
// checked before any of them is saved. No row needs another row, so all of them are
// checked at the same time. The answers come back in the file's own order.
class Row
{
public static function check(string $line): string
{
array<string> $parts = Core\Str::split($line, ',');
if (Core\Arr::count($parts) != 2) {
return 'needs two columns';
}
if (Core\Str::length($parts[1]) == 0) {
return 'the amount is empty';
}
return 'ok';
}
}
array<string> $upload = [
'COFFEE-1KG,2',
'FILTER-100',
'MUG-BLUE,',
'CUP-RED,4',
];
var $verdicts = Core\Task::map($upload, fn(string $line): string => Row::check($line));
// An array's key is always a `string`, so the row number is converted before it is used.
foreach ($verdicts as string $key => string $verdict) {
echo 'row ', ($key as int) + 1, ': ', $verdict, "\n";
}
Output
row 1: ok
row 2: needs two columns
row 3: the amount is empty
row 4: ok

Details

The function may take no parameters, the value, or the value and the key. A third parameter is E0401. The key is always a string, so fn(int $v, int $k) is E0401. The value parameter must have the type of the array's elements.

The result is an array of the function's return type. Core\Task::map([1, 2], fn(int $v): int => …) returns an array<int>.

The function can be written in place, or be a method reference such as Prices::of. A variable of type callable(int): int works too. A variable of type callable, with no signature, is E0401.

The first argument must be an array. An Iterator or a mixed value is E0401.

An empty array starts no tasks, and the result is an empty array.

What Novis does not have

PHP's concurrency tools do not exist in Novis. Naming one is a compile error.

There is no async keyword, no await on a promise, no Fiber, and no pcntl_fork, pthreads, parallel or curl_multi_init. A method that waits just waits, and the code around it is ordinary code. Run several jobs at the same time with Core\Task::all, or one job per element with Core\Task::map. Run a whole file or a static method beside your program with spawn script, and read its result with await. There is no spawn worker, and an anonymous function is not allowed as the entry.

Nothing is shared between requests, or between a spawned file and your program. global, $GLOBALS and a static variable inside a function are compile errors. Values cross at await.

The examples below show Core\Task::all in place of promises, spawn script in place of pcntl_fork, and a page that gets a price from three shops at the same time. The last one shows that new Fiber does not compile.

Core task in place of async and promises

<?nvs
// Shows the replacement for `async` and a promise. `Core\Task::all` takes a set of
// functions, runs them at the same time, and returns all their results together.
class Orders
{
public static function total(): int
{
return 3 + 4;
}
public static function title(): string
{
return 'Orders';
}
}
// No function here is marked `async`, and none of them returns a promise.
// Each field is a function that takes no arguments.
var $page = Core\Task::all({
total: Orders::total,
title: Orders::title,
note: fn(): string => 'ready',
});
// The results are ready on this line. `Core\Task::all` returns only when every
// function has finished. This prints Orders: 7 (ready).
echo $page->title, ': ', $page->total, ' (', $page->note, ")\n";
Output
Orders: 7 (ready)

Spawn script in place of fork and threads

<?nvs
// Shows the replacement for `pcntl_fork` and threads. `spawn script` runs a whole
// file, or a static method, beside your program. Both kinds of entry have a name.
class Report
{
public static function build(int $days): string
{
return 'sales for ' . $days . ' days';
}
}
// The first kind of entry is a file. The path starts at the folder of this file.
var $file = spawn script 'scripts/count-orders.nvs' with(output: 'capture');
// The second kind is a static method, written `Class::method`. `arguments:` gives it
// the values its parameters need.
var $method = spawn script Report::build with(arguments: ['days' => 7]);
// An anonymous function is not allowed as the entry, because it captures variables.
// A spawned file shares nothing with your program except compiled code.
// `await` waits for one entry and gives you its result.
var $counted = await $file;
var $built = await $method;
int $orders = $counted->value as int;
tainted string $text = $built->value as string;
echo 'orders: ', $orders, "\n";
echo 'report: ', $text, "\n";
Output
orders: 1200
report: sales for 7 days

Three shops priced at the same time

<?nvs
// Shows a real use: a product page needs a price from three shops before it can be
// drawn. `Core\Task::map` runs one job per element and returns the answers under the
// same keys, in the same order, whatever order the jobs finished in.
class Shop
{
// A real program would ask the shop over the network here. Each call returns its
// own answer, so no job writes into storage another job can read.
public static function priceIn(string $city): int
{
array<int> $board = ['Hamburg' => 700, 'Munchen' => 750, 'Koln' => 680];
return $board[$city];
}
}
array<string> $shops = ['north' => 'Hamburg', 'south' => 'Munchen', 'west' => 'Koln'];
var $prices = Core\Task::map($shops, fn(string $city): int => Shop::priceIn($city));
// This prints north: 700, then south: 750, then west: 680.
foreach ($prices as string $region => int $cents) {
echo $region, ': ', $cents, "\n";
}
Output
north: 700
south: 750
west: 680

There is no fiber class

<?nvs
// Shows that there is no `Fiber` class, so this program does not compile.
// Run the work as a task with `Core\Task::all` or `Core\Task::map`.
// proof: compile-error
var $fiber = new Fiber(fn(): int => 1);
Output
error[E0303]: `Fiber` is not declared
--> 04-there-is-no-fiber-class.nvs:6:18
|
6 | var $fiber = new Fiber(fn(): int => 1);
| ^^^^^ no matching declaration
error: aborting due to 1 error
To read what a code means and how to fix it, run `nvs agent show <code>`.

Details

Thread, Promise and parallel\Runtime are not classes. new Thread() is E0303, and the message names no replacement.

pcntl_fork() and curl_multi_init() are E0320, because Novis has no functions outside a class.

spawn worker "x.nvs" is a general syntax error. The first error is E0319 for spawn, and it names no replacement.

global $x; is E0204, $GLOBALS is E0211, and static int $n = 0; inside a method is E0209. Their help names a static property, a constant or a parameter.

Nothing is shared between two web requests. Each request has its own variables and static properties.

  • Do use Core\Task::all for a few different calls, like loading a user and their orders.
  • Do use Core\Task::map for the same call on many values, like fetching many URLs.
  • Do give each function a return type, so each result has a type.
  • Don’t write async or await around a call that waits. The call already waits.