0

I am spawning two threads:
a) for user interaction "GUI", pyside2 MainWindow(QtWidgets.QMainWindow) and
b) for visualisation "VIZ" , pygame

Each thread is given two queues "Qin" and "Qout" for inter-thread communication.

My goal is to trigger actions on either side upon receiving messages in the thread's "Qin" which have been sent from the other thread's "Qout".

My approach so far seems a bit "hacky" and I am seeking advice if there may be a better design pattern. I am aware that pygame itself is not well threaded optimized but I do not want to use something else.

What I do:
Within the "VIZ" main loop I read the Q and take action like this

if not queue_in.empty():
    cmd, args = queue_in.get(False)
    print(f"[V] {cmd=}, {args=}")
    if args:
        globals()[cmd](*args)
    else:
        globals()[cmd]()

I take a similar approach on the "GUI" side
Since - for whatever reason - globals()[cmd](*args) does not work , within __init__() I have defined
self.callables = {
    "quit_menu": self.quit_menu,
    "fülle_Verbrauchseinheiten": self.fülle_Verbrauchseinheiten,
}

I read the Qin via
self.timer = QTimer(self)
self.timer.timeout.connect(self.receive_state)
self.timer.start()

def receive_state(self):
    if not self.queue_in.empty():
        cmd, args = self.queue_in.get(False)
        print(f"[G] {cmd=}, {args=}")
        if args:
            self.callables[cmd](*args)
        else:
            self.callables[cmd]()

Effectively I am calling a function/method in a thread by sending the call (with args) through the Q.
As I have pointed out: This seems hacky and maybe "overcomplicated". Before I proceed I want to make sure that I am going in the right direction.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Fab
  • 213
  • 3
  • 15
  • https://stackoverflow.com/questions/35160417/threading-queue-working-example Just check this link you will get a better idea around this. – Deepak Tripathi May 06 '22 at 07:08
  • You can certainly use a queue, see [this](https://stackoverflow.com/questions/20519420/using-threading-in-pygame/20521359#20521359) or [this](https://stackoverflow.com/questions/54209439/python-3-non-blocking-synchronous-behavior/54213423#54213423) example. But note that pygame's event handling only works in the main thread. Maybe try something like [this](https://stackoverflow.com/questions/38280057/how-to-integrate-pygame-and-pyqt4) without the need of threads. – sloth May 06 '22 at 08:37

0 Answers0