スレッドジョブのタイムアウトを実装するための最もよく知られている方法は何ですか (つまり、最大 X 秒後にジョブを強制終了します)? 以下のpythonコードを書きました。これを実装するさまざまな方法を読みましたが、少し迷っています...タイマーでこれを行う必要がありますか? またはコールバックでカウントすることによってadd_timeout
?
補足としてthread.join(timeout)
、メインスレッドをブロックするため、gtk/スレッドアプリケーション内での使用はかなり制限されていますか?
ありがとう !!
注:私はpython/threadingにかなり慣れていません
#!/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 !"