【问题标题】:what is best way to implement thread maximum execution time (in python/gtk)?实现线程最大执行时间的最佳方法是什么(在 python/gtk 中)?
【发布时间】:2013-04-16 10:27:24
【问题描述】:

实现线程作业超时的最佳实践是什么(即:在最多 X 秒后终止作业)? 我写了以下python代码。我读了很多不同的方法来实现这个,但我有点迷茫......我必须用计时器来做这个吗?还是通过计算add_timeout 回调?

作为旁注,thread.join(timeout) 在 gtk/线程应用程序中的使用非常有限,因为它阻塞了主线程?

谢谢!!

注意:我对 python/线程很陌生

#!/usr/bin/python

import time
import threading
import gobject
import gtk
import glib
gobject.threads_init()


class myui():
    def __init__(self):
        interface = gtk.Builder()
        interface.add_from_file("myui.glade")
        interface.connect_signals(self)

        self.spinner = interface.get_object('spinner1')         

    def bg_work1(self):
        print "work has started"
        # simulates some work
        time.sleep(5)
        print "work has finished"

    def startup(self):
        thread = threading.Thread(target=self.bg_work1)
        thread.start()

        # work started. Now while the work is being done I want
        # a spinner to rotate
        self.spinner.start()
        print "spinner started"

        #thread.join() # I wanna wait for the job to be finished while the spinner spins.
                                    # but this seems to block the main thread, and so the gui doesn't shows up !

        glib.timeout_add(100, self.check_job, thread, 5)

    def check_job(self, thread, timeout):
        #print 'check job called'

        if not thread.isAlive():
                print 'is not alive anymore'
                self.spinner.stop()
                return False
        return True


if __name__ == "__main__":

    app = myui()
    app.startup()

    print "gtk main loop starting !"

    gtk.main()
    print "gtk main loop has stopped !"

【问题讨论】:

    标签: python multithreading timeout pygtk


    【解决方案1】:

    您的代码看起来不错,唯一缺少的是使用和评估超时点:

        glib.timeout_add(100, self.check_job, thread, time.time() + 5)
    
    def check_job(self, thread, timeout):
        #print 'check job called'
    
        if not thread.isAlive():
                print 'is not alive anymore'
                self.spinner.stop()
                return False
        if time.time() > timeout:
                print 'job timed out'
                self.spinner.stop()
                return False
        return True
    

    但是,这不会在超时后杀死您的工作线程,因此它仍然会运行。我不知道强制终止 Python 线程的方法。您必须拆分工作并检查工作线程中的超时,以便它可以正常终止。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      • 2015-07-24
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多