The Python Oracle

How to stop background thread in Python

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Future Grid Looping

--

Chapters
00:00 Question
01:27 Accepted answer (Score 1)
02:11 Thank you

--

Full question
https://stackoverflow.com/questions/5091...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3x #python36 #pythonmultithreading

#avk47



ACCEPTED ANSWER

Score 1


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