From d668f2e6bce319fc2880fca75b27b6f8a32e3c6f Mon Sep 17 00:00:00 2001 From: Amit Gupta Date: Wed, 30 Sep 2020 22:48:19 -0700 Subject: [PATCH 1/2] Added support for terminating a spawned worker if a timeout is reached --- lib/parallel.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/lib/parallel.js b/lib/parallel.js index 9e74681..f18ec13 100644 --- a/lib/parallel.js +++ b/lib/parallel.js @@ -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); }; From 16f75093c9631bf6b59ede96f9d7b470620aa7f3 Mon Sep 17 00:00:00 2001 From: Amit Gupta Date: Mon, 5 Oct 2020 12:01:39 -0700 Subject: [PATCH 2/2] added documentation on the new timeout options --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f3eef77..dcf40c1 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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**