Multithreaded JavaScript by Thomas Hunter II

Multithreaded JavaScript by Thomas Hunter II

Author:Thomas Hunter II
Language: eng
Format: epub
Publisher: O'Reilly Media
Published: 2021-09-22T00:00:00+00:00


timed-out

Another thread didn’t call Atomics.notify() within the allotted timeout.

ok

Another thread did call Atomics.notify() in time.

You might be wondering why this method doesn’t throw an error for the first two conditions and silently succeed instead of returning an ok. Because multithreaded programming is used for performance reasons, it stands to reason that calling these Atomics methods will be done in the hotpaths of an application, which are areas where the application spends the most time. It’s less performant in JavaScript to instantiate Error objects and generate stack traces than to return a simple string, so the performance of this approach is pretty high. Another reason is that the not-equal case doesn’t really represent an error case but that something you’re waiting for has already happened.

This blocking behavior might be a little shocking at first. Locking an entire thread sounds a bit intense, and in many cases it is. Another example of what can cause an entire JavaScript thread to lock is the alert() function in a browser. When that function is called, the browser displays a dialog and nothing at all can run—not even any background tasks using the event loop—until the dialog is dismissed. The Atomics.wait() method similarly freezes the thread.

This behavior is so extreme, in fact, that the “main” thread—the default thread that is available when running JavaScript, outside of a web worker—is not allowed to call this method, at least in a browser. The reason is that locking the main thread would be such a poor user experience that the API authors didn’t even want to allow it. If you do try to call this method in the main thread of a browser, you will get one of the following errors:



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.