user2485710 user2485710 - 5 months ago 14
Javascript Question

What does it mean that SpiderMonkey is threadsafe?

I can build SpiderMonkey as a library and use it as a Javascript engine in my C++ application.

In the documentation is been specified that SpiderMonkey is threadsafe, but what does it mean since Javascript/Ecmascript doesn't currently even have a threading model. What kind of calls or expressions are qualified as "safe" with this phrase about SpiderMonkey ? It's just about a piece of C++ code calling any JS functionality from any C++ thread to the Javascript virtual machine ?


Thread-safety of a library means that the library can be used in a multithreaded environment. SpiderMonkey library can be integrated into a multithreaded C++ application. That has nothing to do with JavaScript language model.

However certain rules and restrictions apply. Theses rules are confusing as they have been changing from one version of the library to another and the documentation wasn't and still isn't very clear about them. Documentation pages often display notes like: "Deprecated since..." or "DRAFT IN PROGRESS...", or "Not Found 404".

Starting in Gecko 12.0 or SpiderMonkey 24, the rules are:

  • JSRuntime is single-threaded. You must only use it from one thread
  • To call the library APIs from more that one thread at once, use multiple JSRuntimes
  • In a JS_THREADSAFE build, many JSAPI functions must only be called from within a request (JS_THREADSAFE is now permanently on)
  • Bracket API calls with JS_BeginRequest, JS_EndRequest functions or use JSAutoRequest class
  • Garbage Collector suspends all other threads calling into SpiderMonkey. To keep wait time to a minimum, avoid long-running requests. Do not include blocking I/O or time-consuming calculations inside JS_BeginRequest, JS_EndRequest blocks.

You may consider building a debug version of SpiderMonkey to test your integration. Try using flags:

--enable-root-analysis --enable-debug --disable-optimize

Those add assertions in the library code to help catching thread (garbage collector, and memory) related problems earlier.