From:  Brian Hackett <>
Date:  27 Jan 2017 23:36:19 Hong Kong Time

JS engine multithreading


Bug 1323066 is moving the JS engine to a model where multiple threads
can run JS and otherwise interact with a runtime.  Initially, threads
running JS will be cooperatively scheduled, so at most one thread is
running at once, but the target for bug 1323066 is preemptive
multithreading where different threads can run JS simultaneously.  A
"zone group" abstraction is being introduced, which is a set of zones
and some other data.  A zone group may only be accessed by a single
thread at a time, though over its lifetime multiple threads might
access it at different times.  There will be roughly one zone group
per tab.

Doing this requires some pretty significant structural changes to the
core structures in the engine.  To reduce churn while work on bug
1323066 goes on, most of these structural changes are going into bug
1325050, which shuffles fields around but retains the restriction that
only one specific thread can run JS in the runtime.  This bug sets up
the following roles for each of the main classes:

- JSContext contains all data pertaining to a single thread's state.
Each thread will have a single JSContext which contains its activation
information, other TLS like information about Auto* classes on the
stack, and its current compartment/zone.  The context for the current
thread can be obtained with the TlsContext TLS variable.
ExclusiveContext and PerThreadData have both been removed and folded
into JSContext.

- ZoneGroup contains the data for a zone group described above.
ZoneGroup has a JSContext* field specifying the thread which currently
has exclusive access to its contents.

- JSRuntime may be accessed by multiple threads.  Once we have
preemptive multithreading all the contents of this structure will need
some form of synchronization.  Later on we should be able to use the
main runtime for DOM workers, in which case we'll have a single
runtime in the process and the option of dissolving its members into
static variables.

To help avoid threading bugs during and after this transition, bug
1325050 also adds a ProtectedData class, which is a template that can
be used on class fields to specify the conditions under which the
field may be accessed.  This condition will be checked in debug
builds.  Bug 1325050 uses ProtectedData for all the contents of
JSContext, JSRuntime, Zone, and ZoneGroup (and classes embedded within
these), and it would be nice if people could continue to use this for
new members in these classes going forward.  (Eventually there might
be an analysis to check that ProtectedData is used on all members of
these classes.)

Any thoughts or comments?