简体   繁体   English

如何最好地终止python线程?

[英]How best to terminate a python thread?

In the code below I am creating a thread that opens up a function called candump. 在下面的代码中,我创建了一个打开一个名为candump的函数的线程。 Candump monitors an input channel and returns values to std out as data comes in. Candump监视输入通道,并在数据进入时将值返回到标准输出。

What I want to do is have control over when this terminates (ie, a fixed amount of time after cansend). 我想要做的就是控制何时终止(即cansend之后的固定时间)。 After looking through the documentation it seems like join might be the right way to go? 看完文档之后,似乎加入可能是正确的方法吗?

I'm not sure. 我不确定。 Any thoughts? 有什么想法吗?

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

cited from : Python: kill or terminate subprocess when timeout 引用自: Python:超时时终止或终止子进程

It may not be the best way to terminate a thread, but this answer provides a way to kill a thread. 它可能不是终止线程的最佳方法,但是这个答案提供了一种杀死线程的方法。 Beware that you may also need to implement a way for threads to be unkillable in critical sections of their code. 请注意,您可能还需要实现一种方法,使线程在其代码的关键部分中不可攻击。

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

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