Threading in maya.

So a while back I wanted to create a background thread that checks the user selection at any given point. Now I know I could have done this with a script job but I wanted more flexibility so started looking into threading.

Now threading in maya is somewhat a nightmare as threads are not safe so if a thread crashes so does maya.

But I think I’ve come up with a “somewhat” stable version of threading. I am kind of cheating the function to run on the main thread. This way most Pymel functions will still work correctly without erroring out.

Now be careful though: It can still be unstable especially when using print statements.

The problem is that if one thread gets delayed and the other one starts that there is a slim chance that two or more threads try to do the same operation in maya at the same time. So for example they will both try to move object.vtx[1] to different positions or print to the script editor at the same time it will result in a crash as maya does not know what to do with the situation.

The class here calls the provided function every 1 second. unless specified otherwise. The timer will never be faster than the function takes. so if the function takes 3 seconds to complete then the interval will be 3 seconds even though you might set it to 0.001

It also supports string and mel functions.

Here is the code:

The evalDeferred is the most important part of this class. Without it there is a very high chance that maya will crash as it will most likely try to do two or more operations at the same time.

To see this in action with a funky little example copy this code into a file named:
into your scripts directory. i.e. C:\Users\<username>\Documents\maya\<maya version>\scripts

Now in maya create a poly plane of 100 units wide and high. (make sure you leave the name as default i.e.: “pPlane1”)
and give it 10 subdivisions in each direction.

and run this code:

Now if you are lucky maya dint crash and you will see a flag like motion without the timeline advancing.

VERY IMPORTANT NOTE!!!. if you want to stop the thread run the following code.

DO NOT REDEFINE THE “flagThread” variable as that will lose your chance to kill the thread.

I hope this is of some use to someone. I guess you could even make a simple game with this in maya haha :D.