pygtk应用程序中的单独线程 [英] separate threads in pygtk application

查看:88
本文介绍了pygtk应用程序中的单独线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在处理pyGTK应用程序时遇到一些问题.我给线程一些时间来完成其任务,如果有问题,我还是继续继续,只是警告用户.但是,一旦我继续,该线程就会停止,直到调用gtk.main_quit为止.这让我感到困惑.

I'm having some problems threading my pyGTK application. I give the thread some time to complete its task, if there is a problem I just continue anyway but warn the user. However once I continue, this thread stops until gtk.main_quit is called. This is confusing me.

相关代码:

class MTP_Connection(threading.Thread):
    def __init__(self, HOME_DIR, username):
        self.filename = HOME_DIR + "mtp-dump_" + username
        threading.Thread.__init__(self)

    def run(self):
        #test run
        for i in range(1, 10):
            time.sleep(1)
            print i   

..........................

..........................

start_time = time.time()
conn = MTP_Connection(self.HOME_DIR, self.username)
conn.start()
progress_bar = ProgressBar(self.tree.get_widget("progressbar"),
                           update_speed=100, pulse_mode=True)
while conn.isAlive():
    while gtk.events_pending():
        gtk.main_iteration()
    if time.time() - start_time > 5:
        self.write_info("problems closing connection.")
        break
#after this the program continues normally, but my conn thread stops

推荐答案

首先,不要将threading.Thread子类化,请使用Thread(target=callable).start().

Firstly, don't subclass threading.Thread, use Thread(target=callable).start().

其次,很可能导致明显阻塞的原因是gtk.main_iteration带有参数block,该参数默认为True,因此,当没有要迭代的事件时,对gtk.main_iteration的调用实际上会阻塞.可以通过以下方式解决:

Secondly, and probably the cause of your apparent block is that gtk.main_iteration takes a parameter block, which defaults to True, so your call to gtk.main_iteration will actually block when there are no events to iterate on. Which can be solved with:

gtk.main_iteration(block=False)

但是,没有真正的解释为什么您会使用此被黑客入侵的循环而不是实际的gtk主循环.如果您已经在主循环中运行此程序,那么我建议您做错了事.如果您给我们更多细节和/或完整示例,我可以扩展您的选择.

However, there is no real explanation why you would use this hacked up loop rather than the actual gtk main loop. If you are already running this inside a main loop, then I would suggest that you are doing the wrong thing. I can expand on your options if you give us a bit more detail and/or the complete example.

第三,这只会在以后出现:始终总是总是 总是 ,请确保您已在具有以下功能的任何pygtk应用程序中调用gtk.gdk.threads_init线程. GTK +在运行线程时具有不同的代码路径,因此需要知道如何使用它们.

Thirdly, and this only came up later: Always always always always make sure you have called gtk.gdk.threads_init in any pygtk application with threads. GTK+ has different code paths when running threaded, and it needs to know to use these.

我写了关于pygtk和线程的小文章为您提供了一个小的抽象,因此您不必担心这些事情.该帖子还包含进度条示例.

I wrote a small article about pygtk and threads that offers you a small abstraction so you never have to worry about these things. That post also includes a progress bar example.

这篇关于pygtk应用程序中的单独线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆