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?

dev3dev
  • 128
  • 1
  • 1
  • 9
  • 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 07 '21 at 08: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 07 '21 at 08:30
  • @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 07 '21 at 08:45

1 Answers1

6

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.

jmrk
  • 34,271
  • 7
  • 59
  • 74