node.jstypescriptmultithreading

My worker threads are not being picked up


I'm implementing worker threads in my Node/Typescript application. Now I've come quite far except for the fact that it seems my worker threads are not being picked up/executed. I've added some loggers inside function which should be executed by the worker thread, but for some reason it doesn't show.

I'm calling a function to create a worker. Like this:

create_worker("./src/core/utils/worker.js", {
        term: "amsterdam",
        search_grid: chunked_maps_service![i],
        path: "../../adapters/worker.ts",
})

And this is the function to create a worker:

import { Worker } from "worker_threads";

const create_worker = (file: string, workerData: {}) =>
  new Promise<void>((resolve, reject) => {
    const worker = new Worker(file, {
      workerData: workerData,
    });

    worker.on("message", resolve);
    worker.on("error", reject);
    worker.on("exit", (code) => {
      if (code !== 0)
        reject(new Error(`Worker stopped with exit code ${code}`));
    });
  });

export default create_worker;

Because I'm using typescript I need to compile the typescript code to javascript code to make the worker understand it: Like this:

const path = require("path");
const { workerData } = require("worker_threads");

require("ts-node").register();
require(path.resolve(__dirname, workerData.path));

And then this is the function which should be executed in the worker thread:

import { parentPort } from "worker_threads";

async function worker() {
  console.log("started");
  parentPort.postMessage("fixed!");
}

Is there anything I'm forgetting?


Solution

  • You aren't ever calling the function in your worker.

    This code in the worker:

    import { parentPort } from "worker_threads";
    
    async function worker() {
      console.log("started");
      parentPort.postMessage("fixed!");
    }
    

    Just defines a function named worker. It never calls that function.

    If you want it called immediately, then you must call it like this:

    import { parentPort } from "worker_threads";
    
    async function worker() {
      console.log("started");
      parentPort.postMessage("fixed!");
    }
    
    worker();
    

    FYI, in the worker implementations I've built, I usually either execute something based on data passed into the worker or the worker executes something based on a message it receives from the parent.