I have a main process which spawn one new thread using worker_threads
. Main process in some particular cases have to close this thread without mattering if it has finished its task or not, so MainThread makes use of terminate() to stop the thread. However, this thread spawn different dependencies that need to be closed before exiting. These dependencies have to be closed from the thread, so I cannot use worker.on('exit')
since it is run on main process.
Is there some way of listening the terminate from the worker itself?
Some minimal example of what I would like to achieve.
const {Worker, isMainThread} = require('worker_threads');
if (isMainThread) {
const worker = new Worker(__filename);
worker.on('message', console.log);
worker.on('error', console.log);
worker.on('exit', console.log);
setTimeout(() => {
console.log('Worker is gonna be terminated');
worker.terminate();
}, 5000);
} else {
(async () => {
console.log('I am the worker');
// This thread will spawn its own dependencies, so I want to listen here the terminate signal from
// mainThread to close the dependencies of this worker
// Sth like the following will be awesome
// thread.on('exit', () => { /* close dependencies */ })
// Simulate a task which takes a larger time than MainThread wants to wait
await new Promise(resolve => {
setTimeout(resolve, 10000);
});
})();
}