Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run and stop an infinite loop in a python thread

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?

like image 570
stefano Avatar asked Dec 21 '22 07:12

stefano


1 Answers

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.

like image 143
BrenBarn Avatar answered Jan 07 '23 14:01

BrenBarn