I'm using the nodejs
with worker_threads
module.
I created several workers.
I need to get the id of each worker within the worker itself.
I know that in the cluster
module, just call cluster.worker.id
from within the worker and it returns the worker's id.
I need to do this with worker_threads
, but I don't see a function option to call this from within the worker using when I'm just using threads.
I don't find a function for this in the documentation.
The closest I've come to this is calling worker.threadId
, but that only works on the parent thread.
So I have the expense of forwarding the id through the parent until it reaches the child via postMessage
to the child.
That's too much dirty code.
I miss a function similar to cluster.worker.id
inside a child worker_threads
.
Does anyone know a better solution to calling worker.threadId
from inside a child worker_threads
?
<<< EDIT >>>
The solution has been found!
I found the solution!
You need to add threadId
as an import
of worker_threads
.
import { Worker, isMainThread, parentPort, threadId } from 'worker_threads';
And call threadId
inside the child worker.
The worker id
will come natively.
I asked this question in the official nodejs directory on github.
A person named benjamingr gave this solution. github