Python:无阻塞地排队 [英] Python: queue without blocking
问题描述
我对队列有疑问.我正在用wxpython创建一个GUI,在程序中我需要在单独的线程中做一些事情.线程完成后,我必须修改gui.当另一个线程正在运行时,GUI不应阻塞. 为此,我考虑了队列问题,并写了这样的内容:
I have a question about queues. I am creating a GUI with wxpython, and in the program I need to do something in a separate thread. After the thread finished, I have to modify the gui. The GUI should not block while the other thread is running. For this I thougt about queues and wrote something like this:
def do_something(gui):
# Here it normally does something
gui.queue.put(gui.new)
class GuiFrame(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, title="Test")
self.queue = Queue.Queue()
self.calculate()
def calculate(self):
thread = threading.Thread(target=do_something, args=(self,))
thread.start()
function = self.queue.get()
function()
def new():
# Here something modifies the gui
pass
但是问题是,程序仍然阻塞,我认为是因为队列正在等待某个项目.我可以在新线程中启动它,但是随后我必须再次对队列执行操作,才能在主线程中执行该功能. 有谁能够帮我? 预先谢谢你.
But the problem is now, that the program still blocks, I think because the queue is waiting for an item. I could start it in a new thread, but then I have to do the thing with the queue again, to execute the function in my main thread. Can anybody help me? Thank you in advance.
推荐答案
我建议您使用 wx.CallAfter() .您可能会在此处找到一些有用的示例.您也可以使用 pubsub 模块将消息发送到GUI.然后,您的GUI将不会由于其他线程而阻塞.
I suggest you to use wx.CallAfter(). You may find some useful examples here. Also you can use pubsub module to send messages to your GUI. Then your GUI won't block due to other threads.
这里是一个不错的博客,我当我遇到类似您的问题时,请阅读. 您还可以找到其他基于SO的问题,这些问题可以帮助您理解此概念此处,& 此处
Here is a nice blog that I read when I had a similar issue like yours. You can also find some other questions on SO based that may assist you to understand this concept here, here, & here
这篇关于Python:无阻塞地排队的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!