18+ loke, So, here's my problem:
I have some code running in a webworker. This code is often doing very long-running stuff.
From time to time, the code in the webworker needs to request information from the UI, for example, it may ask the user to enter some information.
Pop quiz: How do I do this, if the code in the webworker cannot return to the event loop?
You'd expect a sane language to give you, well, something like a queue I can send arbitrary data to which can be received by the other thread?
Not JS. Of course not. This is all you get:
You have to use Atomics
Now... How to do it in practice?
Well, this is my attempt
Note that the code is in Kotlin, but it's compiled to JS.
It kinda don't work yet. I've only worked on it for a few hours. But it's my approach.
Why is it so insane? Well, let me tell you:
- The only way to block (and only in a webworker) is to use
Atomics.wait
. This function blocks as long as a single element in aInt32Array
has a specific value.- To change the value, use
Atomics.compareExchange
followed by aAtomics.notify
- To send data from one thread to another, you create a fixed buffer in one thread, send that buffer to the other thread (using a message, so it has to be done in advance), this buffer can then be used for data exchange
Now, figure out how to reliably create a data transfer protocol using these tools. It's not fun.
I know this message doesn't make much sense, but I'm just so exhausted with this, and just needed to post something in an attempt to stay sane.