[python] 關於thread的timer
寫MT實在很惱人,特別是讓threads定期做些事情時,一不小心就busy loop... 先前的做法都是使用os內建的sleep(), 但缺點是無法掌握程式結束的時間。 前幾天偉任建議使用threading模組內建的Timer class 看了做法後,它是使用Event()做為timer, 然後每次invoke一個新的thread去執行該function (其實BT源碼就是這樣做Timer了,只能說當時太弱,不懂期間的差異) 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 setDialogTi...