Goroutines in Dart

A goroutine is a lightweight thread of execution in Dart.

import 'dart:async';

void f(String from) {
  for (int i = 0; i < 3; i++) {
    print("$from : $i");
  }
}

void main() {
  // Calling a function synchronously
  f("direct");

  // Schedule a microtask for the function to run "asynchronously"
  scheduleMicrotask(() => f("microtask"));

  // Using a top-level function in an isolate
  Future(() => f("isolate"));

  // Using an anonymous function in an isolate
  Future(() {
    print("going");
  });

  // Giving time for the isolates to complete
  Future.delayed(Duration(seconds: 1), () {
    print("done");
  });
}

Suppose we have a function call f(s). Here’s how we’d call that in the usual way, running it synchronously.

f("direct");

To invoke this function asynchronously, we can use scheduleMicrotask or Future. This new task will execute concurrently with the calling one.

Using scheduleMicrotask:

scheduleMicrotask(() => f("microtask"));

Using Future:

Future(() => f("isolate"));

You can also start an anonymous function call asynchronously.

Future(() {
  print("going");
});

Our function calls are now running asynchronously. Wait for them to finish.

Future.delayed(Duration(seconds: 1), () {
  print("done");
});

When we run this program, we see the output of the synchronous call first, then the output of the asynchronous calls. The asynchronous output may be interleaved because they are being run concurrently by Dart’s isolates.

$ dart run dart_code.dart
direct : 0
direct : 1
direct : 2
isolate : 0
going
isolate : 1
isolate : 2
done

Next, we’ll look at a complement to asynchronous executions in concurrent Dart programs: Streams.