Dreckr / Worker

Utility for easy concurrency with isolates
MIT License
35 stars 10 forks source link

Worker

Build Status

An easy to use utility to perform tasks concurrently.

By performing blocking CPU intensive tasks concurrently, you free your main isolate to do other stuff while you take advantage of the CPU capabilities.

Usage

To use this library, create a new Worker that will handle the isolates for you, encapsulate your task in class that implements the Task interface and pass it to the Worker to execute it:

void main () {
    Worker worker = new Worker();
    Task task = new AckermannTask(1, 2);
    worker.handle(task).then((result) => print(result));
}

class AckermannTask implements Task {
  int x, y;

  AckermannTask (this.x, this.y);

  int execute () {
    return ackermann(x, y);
  }

  int ackermann (int m, int n) {
    if (m == 0)
      return n+1;
    else if (m > 0 && n == 0)
      return ackermann(m-1, 1);
    else
      return ackermann(m-1, ackermann(m, n-1));
  }
}

You can also define how many tasks a worker can execute concurrently and if the isolates should be spawned lazily:

Worker worker = new Worker(poolSize: 4, spawnLazily: false);

If you want to manage the isolates and SendPorts yourself but still use Tasks, WorkerIsolate comes to the rescue:

WorkerIsolate isolate = new WorkerIsolate();
isolate.performTask(new AckermannTask(1, 2))
        .then(doSomethingAwesome);

Tips