我有一个这样的程序:

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 functionsThread2的父级是Class1,所以当我在Class1中创建线程时:
self.t2 = Thread2(self)
self.t2.start()为什么Thread2要停止Thread1的执行?
发布于 2021-07-26 10:07:47
用不同的话来说,pypubsub的sendMessage实际上是调用您的侦听器函数的,因此等待它返回才能继续。如果这个侦听器函数需要大量时间来运行,那么您所获得的行为显然是线程的“阻塞”。
在这里,您可能希望“发送”一条轻量级消息来触发计算,并以“非阻塞”的方式在另一个地方“侦听”结果。
https://stackoverflow.com/questions/68174615
复制相似问题