Your Location is: Home > Python

What is the easiest way to share data between a GUI event loop and a State Machine that run on multiple threads?

From: Poland View: 3499 Garrison 


I’m working in python with PyQt to build a GUI application that also implements a Finite State Machine (FSM). The state machine is handling devices (e.g. cameras) and the communications with them. So, one of the central states of my FSM is “measure,” which grabs frames from cameras that I want to report back to the GUI.

My first implementation was to trivially put everything on the same thread, but the states can take a while to execute, which leaves the GUI non-responsive; so I wish to multi-thread the application and put the FSM on its own thread; so it doesn’t block the GUI event loop.

I achieved this fine, but it’s a bit clunky to code a new state. It requires passing information from the GUI into the state machine along with controlling the queue of the state machine from the event loop, which are not too bad; however, the state machine then has to report back information to be displayed in the GUI (e.g. images from the cameras).

So, now I have all of this data flying in both directions (from the event loop/GUI into the SM and then from the SM back to the GUI). The ladder in particular requires state dependent data unpacking (I don’t always have cameras connected/images coming back), which is clunky to code.

When I think about the reporting back of the FSM, the main thing I’m doing is updating GUI handles with data from the FSM; so I’m wondering if there is a way to maybe pass in the GUI handles to the FSM class; so I never have to report the images back to the GUI class, for example? Or is there an accepted best practice for passing data back and forth from a GUI class, which in particular has the GUI update methods and the GUI event loop, and the FSM, which in my case controls the devices and the central logic of the program (adaptive feedback using cameras and piezo motors)?

Best answer