Scripting > Python > 

Python and threading

 
 
 

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 )

maya.utils

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:

Creative Commons License Except where otherwise noted, this work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License