Skip to main content
 首页 » 编程设计

python之如何在运行方法中没有循环的情况下终止 Python 中的线程

2025年05月04日12qq号

具有长方法的类。
为该方法创建一个线程。
我如何杀死\终止这个线程?
主要问题是我无法在线程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() 

请您参考如下方法:

这段代码工作正常,但需要明确地从标准输出中刷新数据。
尚未找到无需冲洗即可打印的方法。

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