I need to run a (series of) infinite loops that must be able to check an externally set condition to terminate. I thought the threading module would allow that, but my efforts so fare have failed. Here is an example of what I am trying to do:
import threading
class Looping(object):
def __init__(self):
self.isRunning = True
def runForever(self):
while self.isRunning == True:
"do stuff here"
l = Looping()
t = threading.Thread(target = l.runForever())
t.start()
l.isRunning = False
I would have expected t.start to run in a separate thread, with l's attributes still accessible. This is not what happens. I tried the snippet above in the python shell (IPython). Execution of t start immediately after instantiation and it blocks any further input. There is obviously something I am not getting right about the threading module. Any suggestion on how to solve the problem?
You are calling runForever
too early. Use target = l.runForever
without parentheses.
A function call is not evaluated until after its arguments are. When you write runforever()
, it calls the function right then, before even creating the thread. By just passing runForever
, you pass the function object itself, which the threading apparatus can then call when it is ready. The point is that you don't actually want to call runForever
; you just want to tell the threading code that runForever
is what it should call later.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With