Skip to content

Commit

Permalink
Added support for terminating a spawned worker if a timeout is reached (
Browse files Browse the repository at this point in the history
  • Loading branch information
amit777 authored Oct 6, 2020
1 parent 6bbf617 commit 1dedd68
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ console.log(p.data); // prints [1, 2, 3, 4, 5]

---

### `spawn(fn)`
### `spawn(fn, opts)`

This function will spawn a new process on a worker thread. Pass it the function you want to call. Your
function will receive one argument, which is the current data. The value returned from your spawned function will
Expand All @@ -65,6 +65,8 @@ update the current data.
**Arguments**

* `fn`: A function to execute on a worker thread. Receives the wrapped data as an argument. The value returned will be assigned to the wrapped data.
* `opts`: An optional object to pass to spawn.
* 'opts.timeout': milliseconds to way for function to return value. If the worker does not finish in this time, it will be killed.

**Example**

Expand Down
13 changes: 13 additions & 0 deletions lib/parallel.js
Original file line number Diff line number Diff line change
Expand Up @@ -190,18 +190,31 @@
Parallel.prototype.spawn = function(cb, env) {
const that = this;
const newOp = new Operation();
let timeout;

env = extend(this.options.env, env || {});

this.operation.then(() => {

if(env.timeout) {
timeout = setTimeout(function() {
if(!newOp.resolved) {
wrk.terminate();
newOp.resolve(new Error('Operation timed out!'), null);
}
}, env.timeout);
}

const wrk = that._spawnWorker(cb, env);
if (wrk !== undefined) {
wrk.onmessage = function(msg) {
if(timeout) clearTimeout(timeout);
wrk.terminate();
that.data = msg.data;
newOp.resolve(null, that.data);
};
wrk.onerror = function(e) {
if(timeout) clearTimeout(timeout);
wrk.terminate();
newOp.resolve(e, null);
};
Expand Down

0 comments on commit 1dedd68

Please sign in to comment.