如何在run方法中终止没有循环的Python中的线程? [英] How to terminate a thread in Python without loop in run method?

查看:155
本文介绍了如何在run方法中终止没有循环的Python中的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有一个方法很长的类.
为该方法创建线程.
我如何杀死\终止该线程?
主要问题是我无法在线程 run()方法中检查 threading.Event ,因为它不包含循环.
类似的代码如下:

Having class which has a long method.
Creating a thread for that method.
How i can kill\terminate this thread?
Main problem is that i can't check for threading.Event in thread run() method because it doesn't contain loop.
Similar code as here:

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()

推荐答案

此代码可以正常工作,但是需要从标准输出中显式刷新数据.
尚未找到一种无需冲洗即可打印的工作方式.

This code works fine but there is a need to explicitly flush data from standard output.
Haven't found a way where prints would work without flushing.

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()

这篇关于如何在run方法中终止没有循环的Python中的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆