While I understand that JavaScript is inherently single-threaded and generally frowns upon such things, I am wondering if there is any way to get a WebWorker to wait until some data is made available from the main thread without destroying the call stack of the WebWorker.
As this is for a fun project, I can use new technologies and things that won't reliably run on older browsers, and I don't mind esoteric hacks as long as they work.
Some other solutions that I have thought about:
Continuously poll LocalStorage in a loop until there is data at a predetermined key. This would seem to work because LocalStorage updates by other threads should be visible to the current thread even when polled in a loop, judging from all the discussions about the thread safety of LocalStorage and having multiple tabs write to the same LocalStorage key. The drawback of this approach is that it isn't really "waiting", i.e. the worker thread still consumes full CPU usage hammering at LocalStorage. While LocalStorage is usually implemented with locks, it is not possible to hold a LocalStorage lock for extended periods of time (the lock is released once
getItem
orsetItem
returns).ECMAScript 6
yield
. This doesn't work here because it requires all functions in the call stack (until the place you want to yield to) to be marked as generator functions. The place I want to pause my WebWorker has a call stack that contains WebAssembly functions, which can't be marked as generator functions.IndexedDB. This doesn't work because IndexedDB does not support synchronous requests.
I am aware of this similar question, but that question specifically talks about the onmessage
event and was asked in 2012, before yield
and WebAssembly were introduced.
Is there any way to somehow simulate a lock on the WebWorker thread, or otherwise, so that it would wait until some data is available?