top | item 38899698

JavaScript Multithreading (2023)

17 points| W4G1 | 2 years ago |github.com

8 comments

order

ivanjermakov|2 years ago

Readme does not explain how it works... I guess it's some wrapper around web workers?

W4G1|2 years ago

Creator here. Yes it's a wrapper around the Web Worker and Node Worker Threads API. In order to create an inline worker, the user provided function is serialized using .toString() and any provided yield statements (which specify outside variables, functions & imports) are extracted. Because JavaScript objects are passed by reference, we can get the references by running the user function on the main thread first (iterating over each yield statement), and stop on the last yield so the main thread doesn't execute the rest of the function. Then, whenever a thread mutates a shared variable, the new value is send or transfered to the main thread, which then updates the variable using the object's reference.

ksjskskskkk|2 years ago

absolutely zero js code needs this but it will be the must-have feature for FE frameworks.

and the world will suffer a multitude of common-for-users-but-edge-cases-for-the-devs triggering all sort of bugs for all of 2024.

mcvfijew|2 years ago

It seems the library has a pretty clear way for error handling. What kind of edge cases are you referring to?

abdellah123|2 years ago

why?

phantomathkg|2 years ago

So that heavy operation doesn't block the main UI thread?

tgv|2 years ago

I do have a function that needs to run in a webworker, as it would block the UI for somewhere between 1s and 30s, but I can't see myself adopting this. It looks readable like normal JS. And so it hides its nature from the casual reader. The package does have the usual deadlock problems, so I totally expect this to cause problems.