This project has moved and is read-only. For the latest updates, please go here.

Thread safety and affinity of the v8 engine

Mar 1, 2013 at 8:15 PM
Could you perhaps elaborate a little on the thread safety of the Clearscript v8 implementation? This is something I think other JS engines I've tried have lacked clear documentation on. Specifically whether the following is ok or not:
  1. Instantiating several subsequent engine contexts on the same thread, i.e.:
    instantiate engine1
    dispose engine1
    instantiate engine 2
    dispose engine 2
  2. Using several contexts on several different threads at the same time (whether supported synchroneously or sequential)
  3. Multi threaded access to one context (whether supported synchronously or sequential)
  4. Nested calls (recursive calls) from one context into another context
Mar 1, 2013 at 9:02 PM
Hello MrIze,

Each V8ScriptEngine instance internally creates one V8 isolate and one V8 context, although we're hoping to make this more configurable in the future. The current design has the following implications for your scenarios:

Scenario 1 is supported.

Scenario 2 is supported. If your contexts are sharing data that is not thread-safe, you must protect it by implementing your own locks.

Scenario 3 is supported, but only one thread at a time will be allowed into the script engine. The V8ScriptEngine_Parallel test (source code here) uses 256 threads to remove 256 items from a list held by one V8 context.

Scenario 4 is supported, but you must maintain your own well-defined lock ordering in order to avoid deadlock. You don't have to implement your own locks (unless, again, your contexts are sharing data that is not thread-safe), but you must make sure that Context A doesn't try to call Context B while Context B is trying to call Context A.

Thanks for your question!
Mar 2, 2013 at 1:23 PM
That's great. I think it's pretty much as good as it gets with the v8 engine.

Thank you once again for a very fast answer :)