2

長いメソッドを持つクラスを持つ。
そのメソッドのスレッドを作成します。
このスレッドを強制終了するにはどうすればよいですか? 主な問題は、ループが含まれていないため、スレッドrun()メソッドでthreading.Event
を チェックできないことです。 ここと同様のコード:

import time
import threading

class LongAction:
    def time_consuming_action(self):
        tmax = 600
        for i in range(tmax):
            print i
            time.sleep(1)
        time.sleep(tmax)
        self.tmax = tmax
        return "Slept well"

class LongActionThread(threading.Thread):
    def __init__(self, la_object):
        self.la = la_object
        threading.Thread.__init__(self)

    def run(self):
        self.la.time_consuming_action()


la = LongAction()
la_thread = LongActionThread(la)
la_thread.start()

# After 5 sec i've changed my mind and trying to kill LongActionThread
time.sleep(5)
print "Trying to kill LongActionThread"
la_thread.kill()
4

2 に答える 2

1

このコードは問題なく動作しますが、標準出力から明示的にデータをフラッシュする必要があります。
フラッシュせずに印刷が機能する方法が見つかりませんでした。

import time
from multiprocessing.process import Process
import sys

class LongAction:
    def time_consuming_action(self):
        tmax = 600
        for i in range(tmax):
            print i
            time.sleep(1)
            sys.stdout.flush()
        time.sleep(tmax)
        self.tmax = tmax
        return "Slept well"
        sys.stdout.flush()

class LongActionThread(Process):
    def __init__(self, la_object):
        self.la = la_object
        Process.__init__(self)

    def run(self):
        self.la.time_consuming_action()

if __name__ == "__main__":
    la = LongAction()
    la_thread = LongActionThread(la)
    la_thread.start()

    # After 5 sec i've changed my mind and trying to kill LongActionThread
    time.sleep(5)
    print "Trying to kill LongActionThread"
    la_thread.terminate()
于 2012-12-12T11:34:44.677 に答える
0

スレッドを強制終了するのは良い考えではありませんが、本当にそうしなければならない場合、最も簡単な解決策は、実行中のセマフォを実装し、時間のかかるメソッドを sub_methods に分割し、サブメソッド間のスレッド ステータスをチェックすることです。

このSOの質問から部分的にコピーされたコード:

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self,la_object):
        super(StoppableThread, self).__init__()
        self.la = la_object
        self._stop = threading.Event()

    def stop(self):
        self._stop.set()

    def stopped(self):
        return self._stop.isSet()

    def run(self):
       self.la.time_consuming_action( self.stopped )

    class La :

      def __init__(self):
      #init here

      def time_consuming_action(self, thread_stop_callback ):

          sub_work1()

          if thread_stop_callback():
             raise 'Thread Killed ! '

          sub_work2()

          if thread_stop_callback():
             raise 'Thread Killed ! '

          sub_work3()

          #etc...
于 2012-12-03T11:59:25.947 に答える