Skip to content

Instantly share code, notes, and snippets.

@mourner
Last active July 26, 2018 16:23
Show Gist options
  • Save mourner/150a10cd6fddd0e27f8d94d2f5c71b14 to your computer and use it in GitHub Desktop.
Save mourner/150a10cd6fddd0e27f8d94d2f5c71b14 to your computer and use it in GitHub Desktop.
import {Worker, Agent} from '@mapbox/workerpool';
// only used on the worker side
export class FibonacciWorker extends Worker {
calculate(num, callback) {
let a = 1;
let b = 0;
for (let i = num; num >= 0; num--) {
const tmp = a;
a += b;
b = tmp;
}
callback(null, b);
}
}
// only used on the main thread
export class FibonacciAgent extends Agent {
calculate(num, callback) {
this.send('calculate', num, callback);
}
};
// main thread entry point
import {WorkerPool, registerAgent} from '@mapbox/workerpool';
import {FibonacciAgent} from './fibonacci.js';
WorkerPool.create(4, './worker_bundle.js');
registerAgent(FibonacciAgent, 'Fibonacci');
for (let i = 0; i < 8; i++) {
const fibonacci = new FibonacciAgent();
fibonacci.calculate(i, (err, result) => console.log(result));
}
// worker entry point
import {registerWorker} from '@mapbox/workerpool';
import {FibonacciWorker} from './fibonacci.js';
registerWorker(FibonacciWorker, 'Fibonacci');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment