1

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?
Mohammad
  • 7,344
  • 15
  • 48
  • 76

1 Answers1

2

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Hi the code above was adopted by a stackoveflow question https://stackoverflow.com/a/9812806/157416 Which seems to have a high up vote. I know the code is creating a loop which is the desired result however by threading I am trying disconnect the looping from the main thread. The OP is asking for how to achieve this. I will have a look at the link you provided. But your answer is just describing what I already know so far. Thank you – Mohammad Sep 27 '17 at 12:16
  • And you missed the **start()** call which is present in the example code. so from that point of view: simply step back and consider if my answer solved your issue, if so, kindly think about accepting. Or letting me know what is missing for you to get there. – GhostCat Sep 27 '17 at 12:18
  • Ok I will be looking into the start() call thank you. – Mohammad Sep 27 '17 at 12:19
  • The start() seems to make it so that the thread runs in parallel, can I ask why calling run() directly doesn't have the same outcome? – Mohammad Sep 28 '17 at 10:32
  • Simple: because that is how **threads** work. A thread is the abstraction allow you to **start** a parallel thread of execution. And the abstraction requires you to **start** that thread in order to well, get it started. This is like asking "why do I have to turn the keys to start the engine - why is just sitting in the car not good enough?" – GhostCat Sep 28 '17 at 10:42