Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1dedd68

Browse files
authored
Added support for terminating a spawned worker if a timeout is reached (#207)
1 parent 6bbf617 commit 1dedd68

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

README.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ console.log(p.data); // prints [1, 2, 3, 4, 5]
5656

5757
---
5858

59-
### `spawn(fn)`
59+
### `spawn(fn, opts)`
6060

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

6767
* `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.
68+
* `opts`: An optional object to pass to spawn.
69+
* 'opts.timeout': milliseconds to way for function to return value. If the worker does not finish in this time, it will be killed.
6870

6971
**Example**
7072

lib/parallel.js

+13
Original file line numberDiff line numberDiff line change
@@ -190,18 +190,31 @@
190190
Parallel.prototype.spawn = function(cb, env) {
191191
const that = this;
192192
const newOp = new Operation();
193+
let timeout;
193194

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

196197
this.operation.then(() => {
198+
199+
if(env.timeout) {
200+
timeout = setTimeout(function() {
201+
if(!newOp.resolved) {
202+
wrk.terminate();
203+
newOp.resolve(new Error('Operation timed out!'), null);
204+
}
205+
}, env.timeout);
206+
}
207+
197208
const wrk = that._spawnWorker(cb, env);
198209
if (wrk !== undefined) {
199210
wrk.onmessage = function(msg) {
211+
if(timeout) clearTimeout(timeout);
200212
wrk.terminate();
201213
that.data = msg.data;
202214
newOp.resolve(null, that.data);
203215
};
204216
wrk.onerror = function(e) {
217+
if(timeout) clearTimeout(timeout);
205218
wrk.terminate();
206219
newOp.resolve(e, null);
207220
};

0 commit comments

Comments
 (0)