4

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?

1 Answer 1

11

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.

1
  • Ah, the parens. They still trip me up (My experience with python is less than a month old). Thanks
    – stefano
    Apr 6, 2013 at 14:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.