The Python language comes with built-in threading support. This functionality is available within Maya, but there are some significant constraints that Python developers need to be aware of.
Maya API and Maya Command architectures are not thread-safe. Maya commands throw an exception if they are called outside the main thread, and use of the OpenMaya API from threads other than the main one has unforeseen side effects.
Despite restrictions, there are many potential uses for threading in Python within the context of Maya; for example, spawning a thread to watch a socket for input. To make the use of Python threads more practical, we have provided a way for other threads to execute code in the main thread and wait upon the result.
The maya.utils.executeInMainThreadWithResult() function takes either a string containing Python code or a Python callable object such as a function. In the latter case, executeInMainThreadWithResult() also accepts both regular and keyword arguments that are passed on to the callable object when it is run.
The script or callable object is executed in the main thread during the next idle event. The thread calling executeInMainThreadWithResult() blocks until the main thread becomes idle and runs the code. Once the main thread is done executing the code, executeInMainThreadWithResult() returns the result. If executeInMainThreadWithResult() is called from the main thread, then it simply runs the code immediately and returns the result.
Because idle events are being used to implement executeInMainThreadWithResult(), it is not available in batch mode.
import maya.utils import maya.cmds def doSphere( radius ): maya.cmds.sphere( radius=radius ) maya.utils.executeInMainThreadWithResult( doSphere, 5.0 )
The maya.utils package is where utility routines that are not specific to either the API or Commands are stored. This module will likely expand in future versions.
Currently, the maya.utils package contains three routines relevant to threading (see the previous section for details on executeInMainThreadWithResult).
There are two other routines in maya.utils:
(Similar to maya.utils.executeInMainThreadWithResult() except that it does not wait for the return value.) It delays the execution of the given script or function until Maya is idle. This function runs code using the idle event loop. This means that the main thread must become idle before this Python code is executed.
There are two different ways to call this function. The first is to supply a single string argument which contains the Python code to execute. In that case the code is interpreted. The second way to call this routine is to pass it a callable object. When that is the case, then the remaining regular arguments and keyword arguments are passed to the callable object.