Coroutines

class Coroutine<@RESUME, @YIELD>
type RESUME

The type passed in to the resume() function, and returned from the suspend() function when the coroutine is resumed.

type YIELD

The type passed in to the suspend() function, and returned from start() and resume() when the coroutine yields.

The Coroutine class in dao enables the user to write code as either generators, or as “green threads.” When a coroutine is created and used to start a function, that function can then suspend the coroutine, causing it to return early with the passed value. The coroutine can then be resumed, allowing the function to pick up where it left off without losing state.

Unlike (for example) python generators, the coroutine can be suspended from any depth within the call stack, not just from the point of entry.

The routine called by the coroutine can either suspend the coroutine by accepting it as its first parameter, or it can have a routine signature that does not include a coroutine as first parameter and obtain access to the coroutine by other means to suspend it.

Example usage:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
load coroutine

routine Test( self :Coroutine<int,string>, par : int )
{
    for( i = 1 : 5 ) io.writeln( i, self.yield( 'index_' + (string) (par*i) ) )
    return 'done'
}

co = Coroutine<int,string>()

io.writeln( co )

a = co.start( Test, 100 )
io.writeln( a )

for( i = 1 : 6 ) io.writeln( co.resume( 100*i ), co.status() )

Coroutine API:

coroutine.start(rout[, ...])

Start a coroutine with the given arguments. The given routine can optionally take a first parameter of type Coroutine. If it does, this coroutine will be passed to it as the first parameter. If not, the first parameter will be the first argument in the argument list.

Parameters:rout (routine) – The routine handled by this coroutine object
Return type:YIELD if the coroutine is suspended, or the return type of :param:`rout` otherwise.
coroutine.suspend(value)
coroutine.suspend()

Suspend the coroutine, returning the given value.

Parameters:value (YIELD) – The value to yield.
Return type:RESUME
coroutine.resume(value)
coroutine.resume()

Resume the coroutine, passing the given value back into the function.

Parameters:value (RESUME) – The value to send back into the function.
Return type:YIELD if the coroutine is suspended, or the return type of the called routine otherwise.
coroutine.status()

Get the coroutine’s current status

Return type:enum <running,suspended,finished,aborted>