dev3dev
dev3dev

Reputation: 158

How to share context between worker threads

I would like to create a worker thread in a node.js app and pass the current context to the new thread, so I would be able to access my variables and functions within the new thread, Is there is a library to support that? And if not can I a least pass an anonymous function between them?

Upvotes: 6

Views: 3754

Answers (1)

jmrk
jmrk

Reputation: 40501

There is no way to share a context with a worker thread. This isn't "an ideology of the Node.js team", instead it's a limitation of the JavaScript language, which doesn't allow concurrency (such as concurrent access to objects from a worker thread).

The one exception is that you can share numerical data between multiple threads by using a SharedArrayBuffer.

Aside from that, the way to send data to or receive it from a worker thread is to use postMessage. See also Node's full worker threads documentation.

For completeness: there is an early-stage proposal to add a new kind of cross-thread-shareable object to JavaScript. As with all early-stage proposals, there's no guarantee that it'll be finalized at all or how long that might take, but it does indicate that there's some interest in this space.

Upvotes: 7

Related Questions