简体   繁体   中英

How to stop background thread in Python

Here is the code snippet for illustration purpose. C1.infinite_loop() method is running as background thread. I want to make sure if somebody presses Ctrl+C then terminate the program gracefully. What method do i need to override and where to handle Ctrl+C signal ? I am thinking to set a flag when Ctrl+C is generated and periodically check inside C1.infinite_loop. If flag is true then come out of the loop ? 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. 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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