task(fn, @key args, suspended, name = void, group)
Create and return a new task. The function fn
is called in this task concurrently with the task that created it.
If specified, args
must be a list of objects. This list will be passed to fn
as its arguments.
Fn
should take as many arguments as there are elements in args
.
The default value of args
is false
, which means
no arguments will be passed to fn
.
If suspended
is true
the task is created in the suspended
state. It can be started later by calling the task_run function.
If provided, name
and group
will identify the task's name and the group it belongs to.
task(^() letfn loop (i = 10)
{ showln(i)
task_sleep(2)
loop(i + 1) })
//> 10
11
12
13
14
15
16
...
// passing arguments to the function executed by a task:
function show_range(start, end)
letfn loop (i = start)
when (i < end)
{ showln(i)
task_sleep(2)
loop(i+1) }
task(show_range, args = [10, 15])
//> 10
11
12
13
14
/*
Simple tasks that don't need arguments can be started by the spawn (!) operator.
The expression that follow the operator will be evaluated in a new task.
As an example, consider the following network server which just "echoes" the message sent by
its client. It handles each client in a separate task. The client-handling logic is contained in
the expression that follows the spawn (!) operator:
*/
let s = tcp_server_stream(2020)
function echo(client)
{ showln(stream = client, read_line(client))
flush_writer(client) }
letfn loop (client = read(s))
{ !call_with_stream(client, echo)
loop(read(s)) }
// The following code can be used to test the echo server:
let c = tcp_client_stream("localhost:2020")
showln(stream = c, "hello")
flush_writer(c)
read_line(c)
//> hello