Threading

Although using Mechanical scripting APIs on a background thread might work in practice, the APIs are generally not thread-safe, and race conditions might and often do occur when trying to access them from a background thread.

It is still possible to only run parts of your code—namely those parts that do not use these APIs and hence do not risk race conditions—on a background thread. To do so, you can offload work to a new thread. A convenient way to do this is by using the InvokeBackground method exposed on ExtAPI.Application. This method can only take a function without any arguments, but the following technique can be used to pass in arguments to that function:

#function that is to be run in the background. It is safe because it does not using any of the Mechanical scripting APIs

def gradient(vectors)
    print("Computing gradients of the vectors”)

#function that is run on the main thread
def my_script(result):
    vectors = some_function(result)
    def invokeInBackground():
        gradient(vectors)
    ExtAPI.Application.InvokeBackground(invokeInBackground)


Note:  A race condition is a software problem that can arise when concurrent code does not synchronize data access and mutation. These conditions are by their nature difficult to identify and reproduce, and they sometimes lead to seemingly random problems. There is no way to predict the outcome of a race condition. Alarmingly, it is possible for code to work well for years and then suddenly start to crash because of a race condition.