kill 和 thread 有不同的方法
- 在上面的代码中,只要设置了
global variablestop_threads,target 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() 杀死线程。