-
Notifications
You must be signed in to change notification settings - Fork 151
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add oncreated worker #481
base: master
Are you sure you want to change the base?
Add oncreated worker #481
Conversation
Thanks @GwiYeong. Thinking aloud here: can we already achieve this already by using events? Would it be possible to let a worker send it's pid to the main process via |
@josdejong Thank you for responding. |
You can indeed only send/receive // myWorker.js
var workerpool = require('workerpool')
var initialized = false
function wrapperSendPidOnce(fn) {
return (...args) => {
if (!initialized) {
initialized = true
workerpool.workerEmit({ type: 'created', pid: process.pid })
}
return fn(...args)
}
}
function add(a, b) {
return a + b
}
function multiply(a, b) {
return a * b
}
workerpool.worker({
add: wrapperSendPidOnce(add),
multiply: wrapperSendPidOnce(multiply)
}) And then use the worker like so: // main.js
var workerpool = require('workerpool')
var pool = workerpool.pool(__dirname + '/myWorker.js')
function execWithEventListener(method, args) {
function handleEvent(event) {
console.log('Event: ', event)
}
return pool.exec(method, args, { on: handleEvent })
}
async function run() {
console.log(await execWithEventListener('add', [2, 3]))
console.log(await execWithEventListener('add', [7, 2]))
}
run()
.catch(function (err) {
console.error(err)
})
.finally(function () {
pool.terminate()
}) Running this example wil output:
Would that address your case? |
@josdejong yes. I understand what you are saying. |
I wanted to add a cpu limit for the worker process created when utilizing workerpool in process mode.
However, the current callback doesn't know the pid of the created worker.
This PR adds a callback to get the information of the created worker after the worker is created.
I added a callback called
onCreatedWorker
, which is passed the currently created WorkerHandler directly.If it's a process worker, I can get the created pid via
worker.worker.pid
.The pid can then be used to limit resources, such as cpu limit.
For cpulimit worker, I add an example.