Re: Sync API for workers

On Mon, Sep 3, 2012 at 10:55 PM, Glenn Maynard <glenn@zewt.org> wrote:

> I suspect there's a way to make the general-case version work, though.
>

To restate this by itself instead of as a delta:

- Add an internal flag to MessagePort, "blocking permitted", which is
initially set.  Add a value "previous owner", which is initially null.
- During postMessage, when a MessagePort "port" is to be transferred, set
the MessagePort's "previous owner" to the current thread.
- When a MessagePort is transferred to the current thread, the current
thread must compare itself to the "previous owner" value of the received
MessagePort:
  - If the current thread is a descendant of previous owner, the "blocking
permitted" flag of "port" must be cleared.  (This is a "down" transfer.)
  - Otherwise, if previous owner is a descendant of the current thread, a
"clear blocking permitted" message must be sent over "port".  (This is an
"up" transfer.)
  - Otherwise, if previous owner is the current thread, do nothing.
  - Otherwise, the "blocking permitted" flag of "port" must be cleared and
a "clear blocking permitted" message must be sent over "port".
- When a "clear blocking permitted" message is received on the a port's
message queue, it must be discarded and the "blocking permitted" flag of
the port must be cleared.
- When the "blocking permitted" flag of any MessagePort is cleared, any
getMessage calls blocking on that port throw an exception.
- Calling getMessage on a port (with a nonzero timeout) whose "blocking
permitted" flag is cleared throws the same exception.
- Additionally, calling getMessage on a port (with a nonzero timeout) when
neither it nor its entangled port has ever been transferred to another
thread throws an exception.  (Blocking for data when the current thread
holds both sides of the port guarantees a deadlock.)

The "compare itself to" step must be allowed to happen asynchronously, as
soon as the port appears in a message queue held by the current thread (and
before the message containing the port is taken from the queue for delivery
to onmessage or getMessage).  That ensures that a long-running script
doesn't prevent the "clear blocking permitted" message from being sent.
That's a bit annoying, but it seems doable, since it has no script-visible
effects in the thread it's happening in.  (This isn't necessary for the
"clear blocking permitted" message; that can simply be processed in port
message queue order.)

-- 
Glenn Maynard

Received on Tuesday, 4 September 2012 22:00:41 UTC