想看英文的可以点击这里
通常来说,突然杀死一个子线程往往不是一个好的选择。但是,在某些特定的场合,我们需要杀死子线程。下面介绍了五种不同的方法杀死子线程:
- Raising exceptions in a python thread
- Set/Reset stop flag
- Using traces to kill threads
- Using the multiprocessing module to kill threads
- Killing Python thread by setting it as daemon
1.
Raising exceptions in a python thread
代码如下:
# Python program raising
# exceptions in a python
# thread
import threading
import ctypes
import time
class thread_with_exception(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
# target function of the thread class
try:
while True:
print('running ' + self.name)
finally:
print('ended')
def get_id(self):
# returns id of the respective thread
if hasattr(self, '_thread_id'):
return self._thread_id
for id, thread in threading._active.items():
if thread is self:
return id
def raise_exception(self):
thread_id = self.get_id()
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id,
ctypes.py_object(SystemExit))
if res > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0)
print('Exception raise failure')
t1 = thread_with_exception('Thread 1')
t1.start()
time.sleep(2)
t1.raise_exception()
t1.join()
当我们运行上面的代码的时候,我们会发现,只要我们调用raise_exception()函数的时候,run()函数就会终止。这是因为只要我们抛出异常的时候,程序就会跳转到try代码块中,然后run()函数就会终止,之后join()函数就会被调用,然后杀死子线程。如果不调用raise_exception()函数的话,run()函数就会一直运行,然后join()函数也永远不会调用去杀死子线程(这是因为我们将run函数放在while循环中)。
2. Set/Reset stop flag
为了杀死一个子线程,我们可以声明一个停止标志位,子线程会检查这个标志位是否为True。比如:
# Python program showing
# how to kill threads
# using set/reset stop
# flag
import threading
import time
def run():
while True:
print('thread running')
global stop_threads
if stop_threads:
break
stop_threads = False
t1 = threading.Thread(target = run)
t1.start()
time.sleep(1)
stop_threads = True
t1.join()
print('thread killed')
在上面的代码中,只要设置了全局变量stop_threads,目标函数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()
在上面的代码中,函数对象传递给了子线程,并且这个函数总是会返回局部变量stop_threads的值。在run()函数中,程序总是会检查stop_threads的值,只要它被重置了,run()函数就会停止,然后子线程就会被杀死。
3. Using traces to kill threads
通过安装traces,这个方法可以在每个线程中都有效。
# 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')
4. Using the multiprocessing module to kill threads
多进程模块允许我们使用向创建一个子线程的方式来创建一个子进程。多进程模块和多线程模块的接口非常相似。举个栗子,我们可以使用三个子线程来打印1-9的所有数字。
# Python program creating
# three threads
import threading
import time
# counts from 1 to 9
def func(number):
for i in range(1, 10):
time.sleep(0.01)
print('Thread ' + str(number) + ': prints ' + str(number*i))
# creates 3 threads
for i in range(0, 3):
thread = threading.Thread(target=func, args=(i,))
thread.start()
因此,我们对上面的代码稍微的修改一下,就可以用相似的方法实现上面相似的功能:
# Python program creating
# thread using multiprocessing
# module
import multiprocessing
import time
def func(number):
for i in range(1, 10):
time.sleep(0.01)
print('Processing ' + str(number) + ': prints ' + str(number*i))
for i in range(0, 3):
process = multiprocessing.Process(target=func, args=(i,))
process.start()
尽管这两个模型的的接口函数非常的相似,但是它们的实现方法却大相径庭。所有的子线程共享全局变量,但是各个进程之间是相互独立的。因此,杀死一个进程远比杀死一个子线程要麻烦的多。Process类提供了一个terminate()方法去杀死一个子进程。
# Python program killing
# a thread using multiprocessing
# module
import multiprocessing
import time
def func(number):
for i in range(1, 10):
time.sleep(0.01)
print('Processing ' + str(number) + ': prints ' + str(number*i))
# list of all processes, so that they can be killed afterwards
all_processes = []
for i in range(0, 3):
process = multiprocessing.Process(target=func, args=(i,))
process.start()
all_processes.append(process)
# kill all processes after 0.03s
time.sleep(0.03)
for process in all_processes:
process.terminate()
5. Killing Python thread by setting it as daemon
当主程序退出的时候,Daemon线程就会被杀死,比如:
import threading
import time
import sys
def func():
while True:
time.sleep(0.5)
print('Thread alive, and it won't die on program termination')
t1 = threading.Thread(target=func)
t1.start()
time.sleep(2)
sys.exit()
需要注意的是,当主程序通过sys.exit()退出的时候,子线程t1仍然存活。在Python中,任何non-daemon的线程都会堵塞主线程,不让主线程退出。但是daemon线程恰好相反,只要主线程退出,daemon线程就会被杀死。为了声明一个线程为daemon线程,我们可以将daemon设置为True。
# Python program killing
# thread using daemon
import threading
import time
import sys
def func():
while True:
time.sleep(0.5)
print('Thread alive, but it will die on program termination')
t1 = threading.Thread(target=func)
t1.daemon = True
t1.start()
time.sleep(2)
sys.exit()
当然,我们可以使用面向对象的思维来实现杀死子线程的方法
import threading
import time
import sys
class Detector(threading.Thread):
def __init__(self):
super().__init__()
def run(self):
while True:
time.sleep(0.5)
print("这个是子线程")
if __name__ == '__main__':
detector = Detector()
detector.daemon = True
detector.start()
time.sleep(2)
sys.exit()