问题描述
GUI
是用 wxPython 制作的,位于主线程中。启动应用程序后,GUI 线程创建 Thread1
,它创建一个静态类 Class1
,它创建 Thread2
。
Thread1 使用 wx.PostEvent
与 GUI 对话,一切正常。我还需要 Thread1 与 Thread2 进行通信,所以我决定使用 pyPubSub 来做到这一点。 Thread2 需要在后台工作,因为它包含一些定期执行的操作,但它也包含 Thread1 需要在某些事件上调用的函数(假设 my_func()
)。我决定将 my_func()
放在 Thread2 中,因为我不希望它停止 Thread1 的执行,但这正是发生的情况:在 Thread1 中,在某些事件之后我使用 pub.sendMessage("events",message="Hello")
来触发 my_func()
; Thread2 的结构如下:
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
Thread2 的父类是 Class1,所以当我在 Class1 中创建线程时:
self.t2 = Thread2(self)
self.t2.start()
为什么 Thread2 会停止 Thread1 的执行?
解决方法
换句话说,在评论中,pypubsub 的 sendMessage
实际上是调用您的侦听器函数,因此在继续之前等待它返回。如果此侦听器函数需要大量时间来运行,那么您获得的行为就是线程的明显“阻塞”。
在这里,您可能希望以“非阻塞”方式“发送”轻量级消息以触发计算并在另一个地方“收听”结果。