如何在Python中停止后台线程

时间:2018-06-18 14:12:35

标签: python python-3.x python-3.6 python-multithreading

以下是用于说明目的的代码段。 C1.infinite_loop()方法作为后台线程运行。我想确定是否有人按下Ctrl + C然后优雅地终止程序。我需要覆盖什么方法以及在哪里处理Ctrl + C信号?我想在生成Ctrl + C时设置一个标志,并定期检查C1.infinite_loop。如果flag为true则退出循环?这是正确的方法,还是你建议别的什么?

import time
import random
from threading import Thread

class C1:
   def __init__(self):
     self.list = list()

   def infinite_loop(self):
     while True:
       self.list.append(random.randint(1,10))
       time.sleep(2)

class C2:
   def __init__(self):
       print('inside C2 init')
       self.c1 = C1()
   def main(self):
      self.bg_th = Thread(target=self.c1.infinite_loop)
      self.bg_th.start()
   def disp(self):
      print(self.c1.list)

c2 = C2()
c2.main()
time.sleep(2)
c2.disp()
c2.bg_th.join()

还有一个问题。列表在这里的两个线程之间共享。 C2正在读取,C1正在写入。在这种情况下我还需要使用锁吗?

1 个答案:

答案 0 :(得分:1)

这使用标志和信号终止无限循环

#!/usr/bin/env python
import signal
import sys

import time
import random
from threading import Thread

class C1:
   def __init__(self):
      signal.signal(signal.SIGINT,self.signal_handler)
      self.keepgoing = True
      self.list = list()

   def infinite_loop(self):
      while self.keepgoing:
         self.list.append(random.randint(1,10))
         time.sleep(2)

   def signal_handler(self, sig, frame):
       print('You pressed Ctrl+C!')
       self.keepgoing = False

class C2:
   def __init__(self):
      print('inside C2 init')
      self.c1 = C1()

   def main(self):
      self.bg_th = Thread(target=self.c1.infinite_loop)
      self.bg_th.start()

   def disp(self):
      print(self.c1.list)



c2 = C2()
c2.main()
time.sleep(2)
c2.disp()
c2.bg_th.join()