[python] 關於thread的timer

寫MT實在很惱人,特別是讓threads定期做些事情時,一不小心就busy loop...

先前的做法都是使用os內建的sleep(),  但缺點是無法掌握程式結束的時間。
前幾天偉任建議使用threading模組內建的Timer class
看了做法後,它是使用Event()做為timer,  然後每次invoke一個新的thread去執行該function
(其實BT源碼就是這樣做Timer了,只能說當時太弱,不懂期間的差異)

Results:
  1. import threading
  2. import thread
  3.  
  4. mutex = thread.allocate_lock()
  5. def printm(msg):
  6.     with mutex:
  7.         print "[%s]" % threading.current_thread().name,"say:", msg
  8.  
  9.  
  10. class MyThread(threading.Thread):
  11.     def __init__(self, name):
  12.         threading.Thread.__init__(self)
  13.         self.name = name
  14.         self.timer = threading.Event()
  15.    
  16.     def do_dialog(self):
  17.         printm("How do you do?!")
  18.         self.setDialogTimer()
  19.    
  20.     def setDialogTimer(self):
  21.         self.timer.wait(3)
  22.         if not self.timer.is_set():
  23.             self.do_dialog()
  24.                        
  25.     def cancelDialogTimer(self):
  26.         self.timer.set()
  27.        
  28.     def run(self):
  29.         self.setDialogTimer()
  30.         printm("the end.")
  31.  
  32.  
  33. mt = MyThread('mt_thread')
  34. mt.daemon = True
  35. mt.start()
  36.  
  37. my_clock = threading.Event()
  38. printm('my start')
  39. while True:
  40.     try:
  41.         my_clock.wait(10)
  42.         printm('is blocked?')
  43.     except KeyboardInterrupt:
  44.         my_clock.set()
  45.         mt.cancelDialogTimer()
  46.         break
  47. #mt.join()   
  48. printm('my bye')
  49.  




嗯...距離上一次寫blog剛好一個月 = =   三月看來混太大了...

Comments

Popular posts from this blog

股票評價(Stock Valuation) - 股利折現模型

openwrt feed的使用

How to convert Markdown into HTML