Search code examples
pythonclassinfinite-loop

Python: Is there a way of stopping an inifinite loop running on a python Class method?


I am running a loop on a python Class method that depends on a boolean variable. When I try to change the value of the variable from outside, it seems like it is stucked in the loop and I cannot change nor run the next lines.

import time
class Test:
    def __init__(self):
        self.counter = 0
        self.boolean = True
    
    def test1(self):
        while self.boolean:
            time.sleep(0.5)
            print(self.counter)
            self.counter += 1


class Test2:
    def __init__(self):
        self.test = Test()
        self.test.test1()
        
    def stop_test(self):
        time.sleep(2)
        print("Now I change the boolean value")
        self.test.boolean = False

test = Test2()
print("What is going on?")
test.stop_test()

This code sums up my problem.

I expected the loop to end, but instead the loop keeps running and the code is only printing the value of self.counter


Solution

  • You can acheive by threading, something like:

    import time
    import threading
    
    class Test:
        def __init__(self):
            self.counter = 0
            self.boolean = True
        
        def test1(self):
            while self.boolean:
                time.sleep(0.5)
                print(self.counter)
                self.counter += 1
    
    class Test2:
        def __init__(self):
            self.test = Test()
            self.thread = threading.Thread(target=self.test.test1)  # Run test1 in a separate thread
            self.thread.start()  # Start the thread
            
        def stop_test(self):
            time.sleep(2)
            print("Now I change the boolean value")
            self.test.boolean = False
    
    test = Test2()
    print("What is going on?")
    test.stop_test()