What does it mean that SpiderMonkey is threadsafe?

977 views Asked by At

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 ?

2

There are 2 answers

2
dmitri On BEST ANSWER

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.

4
EyalAr On

It's threadsafe in regard to your C++ application. You can use the library from multiple threads inside your C++ code, without concern for locking data structures, etc.

In this context, it's irrelevant what the library does (in your case, execute JS code). What matters is that the library itself can be used in a multithreaded environment.

From Wikipedia:

Implementation is guaranteed to be free of race conditions when accessed by multiple threads simultaneously.

Read more about thread safety in Wikipedia.