How to share context between worker threads
Asked Answered
A

1

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?

Araby answered 7/9, 2021 at 8:1 Comment(3)
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.Parallelogram
@Parallelogram 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.Araby
@Araby 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.Housekeeper
T
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.

Tonsillotomy answered 7/9, 2021 at 10:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.