5

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?

3
  • 1
    The idea of threads is that they're completely closed off from other processes, because they run on a different cpu core and may be in a totally different state / speed. That's why you can't access the original thread that started it.
    – Kokodoko
    Sep 7, 2021 at 8:17
  • @Kokodoko In other programming languages it's possible, so I don't think it's about technical limitations, but more of an ideology of the Node.js team.
    – dev3dev
    Sep 7, 2021 at 8:30
  • 1
    @dev3dev Traditionally JavaScript runs synchronously. Because of this, it does not know semaphores. But semaphores are necessary to share data among two or more threads running in parallel.
    – ceving
    Sep 7, 2021 at 8:45

1 Answer 1

7

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.