Python で Thread

since 2014-03-27

http://docs.python.jp/2/library/threading.html

スレッドを使うプログラムが Ctrl-C で止まらない件

http://methane.hatenablog.jp/entry/20110518/1305715919

http://stackoverflow.com/questions/11436502/closing-all-threads-with-a-keyboard-interrupt

Queue と組み合わせる。

http://bty.sakura.ne.jp/wp/archives/84

こんな感じで、キーボード割り込みでもタイマーでも終わらせられる並列処理が書けそうという話:

import threading
from Queue import Queue
import time
 
RUNNING_TIME_IN_SEC = 60
 
queue = None
 
class Runner(object):
 
    def __init__(self):
        self.startTime = time.time()
 
    def isRunning(self):
        return time.time() - self.startTime < RUNNING_TIME_IN_SEC
 
def timeKeeper(runEvent):
    runner = Runner()
    while runEvent.is_set() and runner.isRunning():
        time.sleep(1)
    print "timeKeeper: finished"
    queue.put("finished")
 
def timedOutput(runEvent):
    while runEvent.is_set():
        time.sleep(2)
        print time.time()
 
if __name__ == "__main__":
    queue = Queue()
    runEvent = threading.Event()
    runEvent.set()
    t1 = threading.Thread(target = timeKeeper, args = (runEvent,))
    t2 = threading.Thread(target = timedOutput, args = (runEvent,))
    t1.start()
    t2.start()
 
    try:
        while True:
            time.sleep(1.0)
            if not queue.empty():
                print "queue not empty"
                if queue.get_nowait() == "finished":
                    print "recieved 'finished'"
                    break
    except KeyboardInterrupt:
        print "attempting to close threads."
    runEvent.clear()
    t1.join()
    t2.join()
    print "threads successfully closed"
python_thread.txt · 最終更新: 2014/03/27 04:27 by Takuya Nishimoto
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0