如何“杀死” Python的线程的两个方式

我经常被问到如何杀死一个后台线程,这个问题的答案让很多人不开心: 线程是杀不死的。在本文中,我将向您展示 Python 中用于终止线程的两个选项。

如何“杀死” Python的线程的两个方式_第1张图片

 

  如果我们是一个好奇宝宝的话,可能会遇到这样一个问题,就是:如何杀死一个 Python 的后台线程呢?我们可能尝试解决这个问题,却发现线程是杀不死的。而本文中将展示,在 Python 中用于终止线程的两个方式。

1. 线程无法结束

· A Threaded Example

  下面是一个简单的,多线程的示例代码。

 import random  
  import threading  
  import time  
  def bg_thread():  
      for i in range(1, 30):  
          print(f'{i} of 30 iterations...')  
          time.sleep(random.random())  # do some work...  
      print(f'{i} iterations completed before exiting.')  
  th = threading.Thread(target=bg_thread)  
  th.start()  
  th.join() 

  使用下面命令来运行程序,在下面的程序运行中,当跑到第 7 次迭代时,按下 Ctrl-C 来中断程序,发现后台运行的程序并没有终止掉。而在第 13 次迭代时,再次按下 Ctrl-C 来中断程序,发现程序真的退出了。

 $ python thread.py  
  1 of 30 iterations...  
  2 of 30 iterations...  
  3 of 30 iterations...  
  4 of 30 iterations...  
  5 of 30 iterations...  
  6 of 30 iterations...  
  7 of 30 iterations...  
  ^CTraceback (most recent call last):  
    File "thread.py", line 14, in   
      th.join()  
    File "/Users/mgrinberg/.pyenv/versions/3.8.6/

你可能感兴趣的:(学习,干货分享,Python,程序人生,职场和发展,软件测试,python)