I have a program that is structured like this:
The GUI
is made with wxPython and is in the Main Thread. After launching the application, the GUI thread creates Thread1
, which creates a static class Class1
, which creates Thread2
.
Thread1 talks with the GUI using wx.PostEvent
, and everything works fine. I need Thread1 to communicate also with Thread2, so I decided to do that using pyPubSub. Thread2 needs to work in the background because it contains some operations that are executed periodically, but it contains also a function (let's say my_func()
) that Thread1 needs to call on certain events. I decided to put my_func()
in Thread2 because I don't want it to stop the execution of Thread1, but that's exactly what happens: in Thread1 after some events I use pub.sendMessage("events", message="Hello")
to trigger my_func()
; Thread2 is structured like this:
class Thread2(Thread)
def __init__(self, parent):
super().__init__()
self.parent = parent
pub.subscribe(self.my_func, "events")
def run(self):
while True:
# do stuff
def my_func(self, message):
# do other stuff using the message
# call parent functions
The parent of Thread2 is Class1, so when I create the thread in Class1 I do:
self.t2 = Thread2(self)
self.t2.start()
Why does Thread2 stops the execution of Thread1?
To put in different words what was said in the comments, pypubsub's sendMessage
is actually calling your listener function and thus waits for it to return before moving on. If this listener function takes a significant amount of time to run, then the behavior you obtain is an apparent "blocking" of your thread.
Here you probably want to 'send' a lightweight message to trigger the computation and 'listen' to the result in another place, in a 'non-blocking' fashion.