[python] 關於thread的timer
寫MT實在很惱人,特別是讓threads定期做些事情時,一不小心就busy loop...
先前的做法都是使用os內建的sleep(), 但缺點是無法掌握程式結束的時間。
前幾天偉任建議使用threading模組內建的Timer class
看了做法後,它是使用Event()做為timer, 然後每次invoke一個新的thread去執行該function
(其實BT源碼就是這樣做Timer了,只能說當時太弱,不懂期間的差異)
Results:
Results:
- import threading
- import thread
- mutex = thread.allocate_lock()
- def printm(msg):
- with mutex:
- print "[%s]" % threading.current_thread().name,"say:", msg
- class MyThread(threading.Thread):
- def __init__(self, name):
- threading.Thread.__init__(self)
- self.name = name
- self.timer = threading.Event()
- def do_dialog(self):
- printm("How do you do?!")
- self.setDialogTimer()
- def setDialogTimer(self):
- self.timer.wait(3)
- if not self.timer.is_set():
- self.do_dialog()
- def cancelDialogTimer(self):
- self.timer.set()
- def run(self):
- self.setDialogTimer()
- printm("the end.")
- mt = MyThread('mt_thread')
- mt.daemon = True
- mt.start()
- my_clock = threading.Event()
- printm('my start')
- while True:
- try:
- my_clock.wait(10)
- printm('is blocked?')
- except KeyboardInterrupt:
- my_clock.set()
- mt.cancelDialogTimer()
- break
- #mt.join()
- printm('my bye')
嗯...距離上一次寫blog剛好一個月 = = 三月看來混太大了...
Comments
Post a Comment