简体   繁体   English

如何在Python中停止后台线程

[英]How to stop background thread in Python

Here is the code snippet for illustration purpose. 以下是用于说明目的的代码段。 C1.infinite_loop() method is running as background thread. C1.infinite_loop()方法作为后台线程运行。 I want to make sure if somebody presses Ctrl+C then terminate the program gracefully. 我想确定是否有人按下Ctrl + C然后优雅地终止程序。 What method do i need to override and where to handle Ctrl+C signal ? 我需要覆盖什么方法以及在哪里处理Ctrl + C信号? I am thinking to set a flag when Ctrl+C is generated and periodically check inside C1.infinite_loop. 我想在生成Ctrl + C时设置一个标志,并定期检查C1.infinite_loop。 If flag is true then come out of the loop ? 如果flag为true则退出循环? Is this right approach or do you suggest something else ? 这是正确的方法还是你建议别的吗?

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()

One more question. 还有一个问题。 List is shared between two threads here. 列表在这里的两个线程之间共享。 C2 is reading and C1 is writing. C2正在读取,C1正在写入。 Do i still need to use lock in such a case ? 在这种情况下我还需要使用锁吗?

This uses flags and signals to terminate the infinite loop 这使用标志和信号来终止无限循环

#!/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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM