0

I have a program that is structured like this:

enter image description here

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?

Deffo
  • 191
  • 1
  • 8
  • 21
  • 1
    Without knowing the specifics of your threads/functions, thread1 is performing a function and needs it to finish, before moving on. So, it doesn't matter `where` the function is, it still has to wait for it to complete. Unless you know different, in which case we need more detail. – Rolf of Saxony Jun 30 '21 at 11:25
  • @RolfofSaxony shouldn't events allow to continue without waiting? If it's not like that, I could have simply called `t2.my_func()` from Thread1 – Deffo Jul 01 '21 at 07:26
  • `a function (let's say my_func()) that Thread1 needs to call on certain events.` The operative word in that quote is `call`. If that's not what you meant, then we need more detail. What is this function, what does it do? Context! – Rolf of Saxony Jul 01 '21 at 08:20

1 Answers1

0

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.

joubs
  • 123
  • 8