[quickjs-devel] Re: Usage of QuickJS in multi-threaded environments

  • From: Ondřej Jirman <megi@xxxxxx>
  • To: quickjs-devel@xxxxxxxxxxxxx
  • Date: Sun, 4 Aug 2019 22:39:15 +0200

Hi,

On Sun, Aug 04, 2019 at 07:39:52PM +0300, Alexander Rodin wrote:

Hi!

The documentation says the following about multi-threading support.

Inside a given runtime, no multi-threading is supported.

However, it is not clear to me would it be safe to move runtime between
threads without concurrent access from different threads. In particular, I’m
interested in the following use case:

1. Create a runtime in the first thread, make a few JS_Eval-s in it, ensure
   that JS_ExecutePendingJob returns 0.
2. Pass the pointers to JSContext and JSRuntime to the second thread.
3. Use JSContext and JSRuntime to run JS_Eval-s exclusively from the second
   thread.

Sounds good if you also don't keep/use any other references to values
associated with the passed runtime from multiple threads.


I’m also interested would the described above behavior be different for
enabled and disabled CONFIG_ATOMICS.

Looks like atomics are only relevant to the SharedArrayBuffer and those
atomic ops are meant to operate on the integer values inside that array.
So these are not really relevant to thread safety of the JSRuntime as a
whole.

How to use SharedArrayBuffer safely with multiple threads is an interesting
question though. The way it's supposed to be used, typically, would be
to:

- have multiple JSRuntimes in multiple threads
- each creates its own JS_NewArrayBuffer with is_shared true, pointing to the
  same memory location
- now you can use JS atomic operations from differnt JSRuntimes in different
  threads to cordinate data access inside the shared buffer

So pretty much all that is shared is the memory location of the buffer,
everything else is separate for each thread.

regards,
        Ondrej

Thanks,
Alexander

Other related posts: