172 points · by avgp · 9y ago · 67 comments
Combine the limited options options to transfer data quickly, and the limited API available in the worker itself (no version of a DOM, even a gutted one for doing measurements), it is no surprise how few opportunities to use them effectively there are.
When it comes to transferring objects, it is so bad people are resorting to JSON.stringifying messages. [0]
Seems like it would be easy to just add an Immutable Array and Map to the standard library, and let people use that on workers without these silly limitations. What am I missing?
[0] https://nolanlawson.com/2016/02/29/high-performance-web-work...
Basically the "gotchas" are in the browser implementations. Each browser's web worker implementation is a little different, and those little differences (bugs) have huge implications in terms of what you can and can't do. For example: one browser may relay direct worker-to-worker messages via the main thread, so if your main thread is blocked your workers can't talk to each other, and that largely defeats the entire purpose of direct worker-to-worker communication.
Fortunately some of these issues have been fixed since (including that one, if memory serves), but it's slow going. I believe what happened was workers were introduced 5+ years ago, met with little interest initially, and the APIs have rotted for years until recently when interest picked up again, especially since SharedArrayBuffer.
My qualm with SharedArrayBuffer is that it kind of sucks to use in pure JS projects, because you have to serialize/deserialize everything to and from the buffer. With the Emscripten toolchain's pthreads support, as far as I'm aware you just compile your code and the heap lives inside SharedArrayBuffer. You don't have to write boilerplate serialization code, so compared to plain JavaScript it's seamless experience in that regard.
My advice to anyone using web workers in a pure JavaScript project is to use them as their name implies: offloading long-running calculations. If you try to treat them as true threads, you're going to have a bad time. Especially if your inter-worker messaging volume is high and you have frequent interdependent (blocking) calculations.
That said, the work I did was prior to SharedArrayBuffer. For very high-performance projects, it will likely be prudent to use SharedArrayBuffer itself as a messaging medium between workers.
In Web land, the overhead of communication with workers is costly that it makes sense to do things in main thread. Preact had an worker diffing implementation but that was slower.
We once had to unzip on worker and pass to main thread, it was faster just to do it on UI thread.
For the record, Chrome has been working on improving their postMessage performance as of M57 [1], so my benchmark should probably be re-run.
Assuming they end up in the same ballpark as Safari and Edge, the only browser for which stringification would still make sense is Firefox. (And maybe they have improved in the past year too. :))
But a lot of the conclusions from that article came from the fact that non-stringified postMessage perf was so bad in Chrome, which especially impacted performance on Android devices.
[1]: https://twitter.com/cramforce/status/824273332258209792
Here is a longer answer. Node currently uses cooperative multi-tasking. Each function call owns the CPU until it gives up the CPU by returning. Therefore all operations are implicitly atomic. Which makes them very easy to reason about.
As soon as you move to multithreading, NOTHING is atomic unless you lock it. You can even have problems with something as simple as:
globalCounter = globalCounter + 1;
(If one thread is suspended between reading on the RHS and writing on the LHS, another thread can fetch fetch/write the value, and then that update gets lost when the first thread continues execution.)There have been many cooperative async programming systems in the past. Every one that has moved to preemptive (which multi-threading is) has uncovered a lot of subtle, hard to spot, and hard to fix bugs because of losing implicit atomic guarantees.
So you go back to the safe solution of locking everything. But now locking/unlocking takes away a bunch of performance, limits parallelism, and creates the possibility for things like deadlocks. And now you might as well not bother with multiple CPUs! (See Python's GIL for a well-known example of this result.)
The challenge therefore is how to add some pre-emptive multitasking while avoiding creating too many unexpected nasty race conditions.
Aysnc and threads are fundamentally different.
Aysnc refers to intelligently pausing/resuming many different operations. This is fantastic for a lot of tasks, especially tasks that require io. A task can be queued up and a callback can be attached to it. Then, while waiting for some condition to be met, your code can keep running. This results in "non-blocking code," which is familiar to all JS programmers.
Threads, in this context (web workers), refer to CPU cores. The Async model described above is all handled by a single CPU core. Most web applications don't require more than one core, but some do (or, at the very least, the demand is there). Using web workers, you can access other CPU cores, each of which has its own stack and its own separate Async event model.
The problem (from this article) with web workers is that data cannot be shared between CPU cores in JavaScript. Any data you want to pass from your main thread to a web worker must be copied, as in a bitwise copy. This article is about a solution for that, a way to share data between different threads in JavaScript, using a new standard that has been accepted by ECMA.
As far as your question, most of the time you don't want or need your promises or Async code to be handled in another thread. It would be insane to offload every single non-blocking line of code to another thread. Threads are much "heavier" than Async. Languages that have good support for threads also have Async.
However, wrapping web workers inside promises (or async/await) is absolutely something that makes sense, and something you can do now.
Right now workers are mainly used for extreme situations and eventually make it into libraries that others use.
I have created a library called Task.js that surfaces this idea into a promise compatible interface where you can just convert a pure function into a worker function. The end result is a promise supported function thats sends the function to a worker with your provided args and resolves when its done (also supports multiple workers and automatic queuing).
var str = '{}'
await JSON.parseAsync(str);
str = '{"foo": 1}' // this line might run before line abovevar somevalue = async doSomething();
var someExpensiveVAlue = thread doExpensiveThing();
var lotsOfExpensiveThings = Thread.all(threads);
var val = await Task.Run(() => doSomeThreadedWork(param));
Indicates to the runtime that the specified delegate may be run on another thread. This doesn't explicitly start a new thread but rather just allows the delegate to execute on one of the thread pool threads that is managed by the runtime. It uses heuristics to decide how many threadpool threads to maintain and whether to actually use one of them to execute your delegate. A similar model would be very useful to have in JavaScript.
It makes wrangling multiple workers much easier, and doesn't require you to have external JS files. (also works in node.js)
demo: http://s.codepen.io/icodeforlove/debug/ZOjBBB/NjrYzwzWdzLA
Paint the image to a canvas, then grab the imagedata off of it, split it into as many parts as you have threads, then use the "transferrableObjects" property of postMessage to zero-copy transfer the data to each worker to be processed, transferred back, and re-stitched together.
It's pretty powerful and suprisingly easy to work with once you understand it.
[0] is a snippet from the code, but be gentile... It was a personal project where I was trying out polymer 0.5 and made a lot of questionable design choices...
Also, I've heard of the idea of using webworkers as a "first class" platform. That is do all of the core parts of your application in them and only use the "main" thread as a "ui" thread. I haven't gotten a chance to try it out, but it seems like a great idea that could really work well in some SPAs.
[0] https://github.com/Klathmon/stitchpics/blob/master/app/eleme...
Like I say, more than happy to be corrected, because that sort of thing would be incredibly helpful. Really, anything that lets you mess with a disconnected DOM in the background and then attach it in the foreground could be useful but (and, again, I'm very happy to be corrected), I don't think you can do this.
https://developer.mozilla.org/en-US/docs/Web/API/OffscreenCa...
Having said that, if you want fast image manipulation, you're probably better off doing direct manipulation of Uint8Clamped arrays anyway, since that can be much faster.
I saw a library a while ago that was trying to re-implement the canvas primitives using only typed arrays so it was worker safe but I'm not sure what happened to it.
I expected to instantiate a WebWorker with a function, and was surprised to discover you have to give it a separate JavaScript file. It is not easy to adopt.
They are an excellent fit for anything that requires heavy number-crunching, and little or no DOM manipulation or network communication.
Another thing was to offload tasks such as encoding GIF frames, which is also working pretty well.
I guess for off-screen image manipulation (if for whatever reason you can't use WebGL and shaders) you'd have to resort to manual pixel manipulation by sending Uint8ClampedArrays back and forth. At least they're transferable by default.
[0] https://github.com/bvaughn/react-virtualized-select
[1] https://github.com/bvaughn/react-select-fast-filter-options
Edit: Shameless Recruiting Plug. If any of you out there are js performance pros and well acquainted with this sort of thing, please reach out as I'm looking for help optimizing further and I'm a bit out of my depth on some of it. Currently this would be a contract position but could grow to something more if that is desired.
Basically to move as much processing client side as possible/reasonable so the server doesn't have to do it.
* Did not read article yet and am not sure about SharedArray structure.
It has some limitations, but for long lived process intensive and async functions is perfect. It has a really clean and easy syntax where you don't need to learn everything about Web Workers and their APIs to be able to use it.
If you are already using promises you might not even need anything besides wrapping the function in a callback.
if(msg.data.offset + msg.data.length === buffer.byteLength)
While you most likely want to wait for all workers to be done before showing the results. In this code however, the last worker will always finish last because it has more work to do (higher numbers).It's often cheaper to scale horizontally, by spreading the work between physical machines, then to add more cores to a shared memory. So it's not such a big deal to have a single threaded program, and single threaded code is easier to reason about. SharedArrayBuffer will however be nice in JavaScript because it allows optimization is games and such, allowing you to have parallel for loops.
And if I'm wrong, this is the quickest way to get the right info. :)
That being said, I'm not sure you're correct. There is no concern of blocking the main thread, since functions queued up via. `setTimeout()` are not tracked by some non-blocking timer. The queue is only inspected if the stack is empty. So if anything is happening, we just ignore the queue until nothing is happening. `setTimeout()` only guarantees a message will be processed after x milliseconds, not on-time.
https://developer.mozilla.org/en/docs/Web/JavaScript/EventLo...
for(var n=2; n <= Math.floor(Math.sqrt(candidate)); n++)