繁体   English   中英

如何最好地终止python线程?

[英]How best to terminate a python thread?

在下面的代码中,我创建了一个打开一个名为candump的函数的线程。 Candump监视输入通道,并在数据进入时将值返回到标准输出。

我想要做的就是控制何时终止(即cansend之后的固定时间)。 看完文档之后,似乎加入可能是正确的方法吗?

我不确定。 有什么想法吗?

import threading
from subprocess import call, Popen,PIPE
import time

delay=1

class ThreadClass(threading.Thread):
  def run(self):
    start=time.time()
    proc=Popen(["candump","can0"],stdout=PIPE)
    while True:
        line=proc.stdout.readline()
        if line !='':
            print line

t = ThreadClass()
t.start()
time.sleep(.1)
call(["cansend", "can0", "-i", "0x601", "0x40", "0xF6", "0x60", "0x01", "0x00", "0x00", "0x00", "0x00"])
time.sleep(0.01)
#right here is where I want to kill the ThreadClass thread
import subprocess as sub
import threading

class RunCmd(threading.Thread):
    def __init__(self, cmd, timeout):
        threading.Thread.__init__(self)
        self.cmd = cmd
        self.timeout = timeout

    def run(self):
        self.p = sub.Popen(self.cmd)
        self.p.wait()

    def Run(self):
        self.start()
        self.join(self.timeout)

        if self.is_alive():
            self.p.terminate()
            self.join()

RunCmd(["./someProg", "arg1"], 60).Run()

引用自: Python:超时时终止或终止子进程

它可能不是终止线程的最佳方法,但是这个答案提供了一种杀死线程的方法。 请注意,您可能还需要实现一种方法,使线程在其代码的关键部分中不可攻击。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM