Home How to stop threads running infinite loops in python?
Reply: 0

How to stop threads running infinite loops in python?

user8651
1#
user8651 Published in September 19, 2018, 6:44 pm

I've made a program which has a main thread that spawns many other threads by subclassing the threading.Thread class.

Each such child thread runs an infinite while loop, and inside the loop I check a condition. If the condition is true, I make the thread sleep for 1 second using time.sleep(1) and if it's false, then the thread performs some computation.

The program itself works fine and I've achieved what I wanted to do, my only remaining problem is that I seem unable to stop the threads after my work is done. I want the user to be able to kill all the threads by pressing a button or giving a keyboard interrupt like Ctrl+C.

For this I had tried using the signal module and inserted a conditon in the threads' loops that breaks the loop when the main thread catches a signal but it didn't work for some reason. Can anyone please help with this?

EDIT: This is some of the relevant code snippets:

def sighandler(signal,frame):
    BaseThreadClass.stop_flag = True
class BaseThreadClass(threading.Thread):
    stop_flag = False
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self,*args):
        while True:
            if condition:
               time.sleep(1)
            else:
               #do computation and stuff
            if BaseThreadClass.stop_flag:
               #do cleanup
               break
share|improve this question
  • 1
    Get the thread by id and kill them once job done. – MaNKuR Jun 9 at 10:07
  • 1
    I tried reading your code but it didn't work for some reason. Can anyone please help with this? One thing I do know, signals aren't for inter-thread communication. – Yann Vernier Jun 9 at 10:08
  • @mankur the threads use sockets, files etc so I want to perform cleanup before killing them abruptly. – G-man Jun 9 at 10:10

2 Answers 2

active oldest votes
up vote 1 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.344344 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO