Thread Safety in SciPy
SciPy supports use in a multithreaded context via the threading module in
the standard library. Many SciPy operations release the GIL, as does NumPy (and
a lot of SciPy functionality is implemented as calls to NumPy functions) - so
unlike many situations in Python, it is possible to improve parallel
performance by exploiting multithreaded parallelism in Python.
The easiest performance gains happen when each worker thread owns its own array or set of array objects, with no data directly shared between threads. Threads that spend most of their time in low-level code will typically run in parallel.
It is possible to share NumPy arrays between threads, but extreme care must be taken to avoid creating thread safety issues when mutating arrays that are shared between multiple threads - please see the NumPy documentation on thread safety for more details. SciPy functions will not mutate arrays that the user passes in, unless a function explicitly documents that it will do so (which is rare). Hence calling SciPy functions in a threaded fashion on the same NumPy array is safe.
While most of SciPy consists of functions, more care has to be taken with classes and data structures.
Classes that have state, such as some of the integration and interpolation
objects in scipy.integrate and , are typically robust
against being called in parallel. They either accept parallel calls or raise an
informative error. For example, may raise an
for integration methods that do not support
parallel execution.