Thread safety¶
This page explains what the Python extension allows when several threads call it at once.
The extension is built free-threaded when the interpreter is
(Py_GIL_DISABLED).
On that interpreter import rgpot and import rgpot.ase leave the GIL
disabled.
Sub-interpreters are not supported: nanobind declares the module unable to run
in more than one interpreter.
One instance per calling thread¶
A potential object is not a session.
LJPot, LJClusterPot, MorsePot, ExprPot, D3Pot, D4Pot and the Fortran
potentials wrap their kernel in a holder that keeps one kernel instance per
calling thread.
The constructing thread uses the instance built with the object.
Another thread’s first call creates an instance for that thread, under a
per-object mutex that is taken only while the interpreter is detached.
Two threads may therefore call one Lennard-Jones object at the same time.
A kernel that declares Reentrancy::SharedInstance keeps the single instance
for every thread instead.
The per-thread map keeps one instance for every caller thread id other than the constructing thread. A finished thread does not drop its entry. The map grows with the number of distinct threads that have called the object, and it is freed when the object is destroyed. Fortran potentials keep one neighbour table per instance, so each thread also has its own table.
evaluate_batch does not use that map.
It builds one instance per worker, and no more workers than there are
configurations.
The saved parameter block in each Fortran
_capi module is written once, from C++ std::call_once, and is read-only
after that.
The handle-free entry’s legacy workspace is not used by Python.
Other classes, such as StillingerWeberSi and TersoffSiC, hold one kernel
instance and no per-thread map.
Do not call one such object from two threads at once.
What is not reentrant (F5)¶
The ASE calculate path writes self.atoms and self.results.
Do not call get_potential_energy or get_forces on one calculator from two
threads.
The pure protocol __rg_evaluate__ does not mutate the calculator, and that
protocol is the reentrant path.
calculate_many builds one batch and does not mutate the input atoms.
An exception raised on the protocol path is the caller’s; the calculator object
is left as it was.
One connection at a time (F3)¶
The RPC calculator’s connection is the exception to the per-thread workspace
rule.
It is in use by one thread at a time.
A second thread gets RuntimeError naming the calculator type, rather than
sharing the socket.