Re: Synchronous postMessage for Workers?

On Feb 16, 2012, at 7:06 AM, Glenn Maynard wrote:

> On Wed, Feb 15, 2012 at 12:39 AM, Jonas Sicking <jonas@sicking.cc> wrote:
> Put it another way, when you spin the event loop, not only does your
> code need to be prepared for anything happening. All functions up the
> call stack also has to. That makes it very hard to reason about any of
> your code, not just the code that calls yieldUntil.
> 
> FWIW, I've used similar mechanisms, such as Lua coroutines, and it worked well.

It works well when you know that the function you're calling is blocking. As Boris, Mark, and Jonas have said, it doesn't work so well as your code starts growing and you lose track of who might be blocking when.

> The message polling/blocking can be done without spinning the event loop, of course.  It would be nice to have capabilities like running two sync XHRs, but with message blocking, you'd be able to do that yourself with a bit more work (spin up two workers to do the XHRs, then block on response messages).

Using workers for this is heavyweight. It works very nicely in ES6 with task.js:

    spawn(function*() {
        try {
            var [file1, file2] = yield join(xhr("file1.txt"), xhr("file2.txt"));
            element1.innerHTML = file1;
            element2.innerHTML = file2;
        } catch (e) {
            console.log("error: " + e);
        }
    });

The difference between task.js and continuations/coroutines/synchronous workers is that the blocking is always explicitly labelled with `yield`. So you can never accidentally call a function that might suspend your stack and allow other code to run in between.

I wrote about this recently:

    http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/

A commenter correctly pointed out that the worker approach makes it easier for engines to capture native frames, so maybe it's not so onerous for implementors as my post makes it out to be. But we made a conscious choice in TC39 *not* to add full coroutines to JS because of the fragility of implicit suspension.

Dave

Received on Friday, 2 March 2012 19:22:30 UTC