Skip to content
This repository has been archived by the owner on Sep 15, 2022. It is now read-only.

Coroutines and Fibers

Michael Thomsen edited this page May 10, 2016 · 3 revisions

Fibers

Dartino encourages a synchronous way of programming and allows processes to block when they are waiting for events to happen. To avoid always blocking an entire process, Dartino supports running multiple cooperatively scheduled fibers within a process and have them block independently of each other. This means that multiple separate control flows can be modeled explicitly as separate fibers rather than implicitly as it is done with traditional asynchronous coding.

Here's an example of two fibers communicating through a shared channel. The call to channel.receive is blocking so the consumer fiber cannot continue to run until the producer has produced a value for it.

main() {
  var channel = new Channel();
  Fiber.fork(() => producer(channel));
  for (int i = 0; i < 10; i++) {
    print(channel.receive());
  }
}

producer(Channel channel) {
  for (int i = 0; i < 10; i++) {
    channel.send(i);
  }
}

Coroutines

Dartino has built-in support for coroutines. Coroutines are function-like objects that can yield multiple values and as such they are closely related to generators. When a coroutine yields, it is suspended at its current position in the code and the execution stack is preserved until it is later resumed. Once a coroutine runs to completion and returns its final value, it is considered done and can no longer be resumed. Here's a simple example illustrating the use of coroutines:

var co = new Coroutine((x) {
  Expect.equals(1, x);
  Expect.equals(3, Coroutine.yield(2));
  return 4;
});
Expect.isTrue(co.isSuspended);
Expect.equals(2, co(1));
Expect.isTrue(co.isSuspended);
Expect.equals(4, co(3));
Expect.isTrue(co.isDone);

References

[Why Events Are A Bad Idea (for high-concurrency servers)] (https://www.usenix.org/legacy/events/hotos03/tech/full_papers/vonbehren/vonbehren_html/index.html)