【问题标题】:How do I kill this thread in python [duplicate]我如何在python中杀死这个线程[重复]
【发布时间】:2020-08-05 11:50:42
【问题描述】:

在这段代码中

杀死 = 假

a = tr.Thread(target=func, args=(a, b, kill), daemon=True)

a.start()

这是一个 tkinter 应用程序,所以我如何杀死这个线程,就像执行此操作的命令一样。

【问题讨论】:

  • kill 设置为True 并加入线程。无论如何,由于你的线程是一个守护进程,它会在所有其他非守护线程和主线程停止时停止

标签: python multithreading kill func


【解决方案1】:

killthread 有不同的方法

  • 在上面的代码中,只要设置了global variablestop_threadstarget function run()就结束了,线程t1可以使用t1.join()杀死。但是由于某些原因,人们可能会避免使用全局变量。对于这些情况,可以传递函数对象以提供类似的功能,如下所示。
# Python program killing 
# threads using stop 
# flag 
import threading 
import time 
def run(stop): 
    while True: 
        print('thread running') 
        if stop(): 
                break
def main(): 
        stop_threads = False
        t1 = threading.Thread(target = run, args =(lambda : stop_threads, )) 
        t1.start() 
        time.sleep(1) 
        stop_threads = True
        t1.join() 
        print('thread killed') 
main() 

上面代码中传递的函数对象总是返回local variable stop_threads的值。在函数run()中检查这个值,一旦stop_threads被重置,run()函数结束,线程可以被杀死。

  • 使用跟踪杀死线程: 此方法通过在每个线程中安装跟踪来工作。每个跟踪都会在检测到某些刺激或标志时自行终止,从而立即终止相关线程。例如
# Python program using 
# traces to kill threads 

import sys 
import trace 
import threading 
import time 
class thread_with_trace(threading.Thread): 
  def __init__(self, *args, **keywords): 
    threading.Thread.__init__(self, *args, **keywords) 
    self.killed = False
  def start(self): 
    self.__run_backup = self.run 
    self.run = self.__run       
    threading.Thread.start(self) 

  def __run(self): 
    sys.settrace(self.globaltrace) 
    self.__run_backup() 
    self.run = self.__run_backup 
  def globaltrace(self, frame, event, arg): 
    if event == 'call': 
      return self.localtrace 
    else: 
      return None

  def localtrace(self, frame, event, arg): 
    if self.killed: 
      if event == 'line': 
        raise SystemExit() 
    return self.localtrace 
  def kill(self): 
    self.killed = True
def func(): 
  while True: 
    print('thread running') 
t1 = thread_with_trace(target = func) 
t1.start() 

time.sleep(2) 
t1.kill() 
t1.join() 

if not t1.isAlive(): 

  print('thread killed') 

在此代码中, start() 稍作修改以使用settrace() 设置系统跟踪功能。本地跟踪函数被定义为,每当设置相应thread 的终止标志(已终止)时,在执行下一行代码时引发 SystemExit 异常,从而结束目标函数 func 的执行。现在可以使用join() 杀死线程。

【讨论】:

  • 正是我在寻找:D
猜你喜欢
  • 2012-07-11
  • 1970-01-01
  • 2022-11-29
  • 2011-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-09
相关资源
最近更新 更多