Mohammad
Mohammad

Reputation: 7418

Python: How to avoid a 'wait' in a thread stopping the flow of program?

In the example below the timer will keep printing hello world every 5 seconds and never stop, how can I allow the timer thread to function as a timer (printing 'hello world') but also not stop the progression of the program?

import threading
class Timer_Class(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.event = threading.Event()
        self.running = True
    def run(self, timer_wait, my_fun, print_text):
        while self.running:
            my_fun(print_text)
            self.event.wait(timer_wait)

    def stop(self):
        self.running = False




def print_something(text_to_print):
    print(text_to_print)


timr = Timer_Class()
timr.run(5, print_something, 'hello world')
timr.stop() # How can I get the program to execute this line?

Upvotes: 1

Views: 1306

Answers (1)

GhostCat
GhostCat

Reputation: 140427

First of all:

while self.running:

Your code contains a loop that will keep looping until the loop condition self.running is somehow changed to False.

If you want to not loop, I suggest you remove that looping part in your code.

And then: you are not calling start() on your thread object. Therefore you current code does everything on the main thread. In order to really utilize more than one thread you have to call timr.start() at some point!

So the real answer here: step back learn how multi-threading works in Python (for example have a look here). It seems that you have heard some concepts and go trial/error. And that is a very inefficient strategy.

Upvotes: 2

Related Questions