Maya - threading help. UI pause button

Looking for help on threading in Maya, so you can hit “play/pause/stop” on a running script. Is this the basic idea?

scriptA - runs in the main thread. Has a variable “allowed_to_update” that scriptB has access to. Could be a UI, etc. And doesn’t know about scriptB.

scriptB - does the work, and checks with each iteration if it’s allowed to continue working, etc.

Yeah, you have the basics right. I would just wrap both the UI/main thread and the asynchronous thread in a single class that has a variable called pause_thread (or whatever). Set it to False, then launch the thread. When you want to pause the thread, set it to true, and when the thread reads the variable, it can go into a time.sleep loop. http://www.tutorialspoint.com/python/time_sleep.htm

Here is a good thread (ahem) on threading: http://stackoverflow.com/questions/1190206/threading-in-python
Here’s one on data sharing: http://stackoverflow.com/questions/104983/what-is-thread-local-storage-in-python-and-why-do-i-need-it
Make sure you use the Maya threading calls when talking to Maya from a thread: http://download.autodesk.com/us/maya/2010help/index.html?url=Python_Python_and_threading.htm,topicNumber=d0e182779

1 Like

Thank you! I’ll see if I can … (thread joke).

iron this out?

Sleep() function actually suspends the processing of the thread in which it is called by the operating system, allowing other threads and processes to execute while it sleeps. With multiple threads and processes, sleep() suspends your thread - it uses next to zero processing power.

The UI runs on the main thread no? So it will lock as soon as you start scriptA which is also on the main thread.
So you would have to do your processing in the background thread and pause it from the main thread, rather than the other way around.

1 Like

Nowadays I would also consider implementing the tool (UI and functionality) as a coroutine rather than a thread – you have to be so careful with Maya threads anyway that the programming is actually a bit simpler.

There’s an example of a thread-like coroutine system here:

In that universe you’d make the entire thing iterate in the main thread, but run the long task as a coroutine with yields at places where you would want it to be interruptible

1 Like