"is dwscript thread-safe?" Code Answer


arnaud gave the key points:

  • each compiler instance can only be invoked from one thread at a time. you can have multiple compiler instances invoked in multiple threads at the same time, and a particular compiler instance can be used from multiple threads, provided only one thread uses it a time.
  • each compiled program can have multiple executions, each execution can be running in its own thread. also a particular execution can be used by several threads, provided only one thread uses it at a time.
  • each executions has its own space for its variables, and its own stack, object instances are on the heap and can technically be shared across executions, there is no locking mechanism for that, but you could make your own.
  • the script engine does not perform any synchronization or locking when using classes or functions exposed to it (be it via tdwsunit, rtti, etc.), so when running script executions in threads, make sure you only exposed thread-safe stuff (be particularly careful about that for rtti, since lot of the rtl & vcl is not thread-safe to begin with)

running multiple executions of a script is similar to having multiple threads in delphi, though each new execution has not only its own stack (like delphi threads) but also its own variable space (in delphi it would be a bit like if you had "thread var" everywhere). and dwscript executions don't have to be in their own thread, they can be moved across threads, or polled and used in a lower number of threads (the only limitation being that each execution is used by only one thread at a time, as mentioned above).

so nothing prevents you from exposing a function that would spawn a thread (and corresponding execution) in a script function, but communication across the executions wouldn't be via shared variables (like you could be tempted to do in delphi), but would have to go through your own exposed functions (or external variables), return values (using an "evaluate" approach, cf. the unit tests), "shared" object instances, or "global vars".

by "global vars", i mean the functions defined in dwsglobalvarsfunctions.pas, which can be used for inter-execution data exchange. to activate them, just have a "uses dwsglobalvarsfunctions" somewhere in your project.

they expose a set of read/writeglobalvar functions, which allow storing and retrieving named variants across all script executions running within the same delphi process, and those reads & writes are "atomic" from a threading point of view.

By codeVerine on May 7 2022

Answers related to “is dwscript thread-safe?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.