Introduction
Creating a lot of threads gets expensive over time. If it's just necessary to change some input values and then run the thread again, it's faster to reuse a previously created thread. Unfortunately, Python does not support such behaviour.
Here is a class that can rerun a threaded function as often as you want.
Using the Code
The Class Itself
For details, see the comments:
from threading import Thread, Event
class ReusableThread(Thread)
def __init__(self, target, args):
self._startSignal = Event()
self._oneRunFinished = Event()
self._finishIndicator = False
self._callable = target
self._callableArgs = args
Thread.__init__(self)
def restart(self)
self._startSignal.set()
def run(self)
self.restart()
while(True):
self._startSignal.wait()
self._startSignal.clear()
if(self._finishIndicator):
self._oneRunFinished.set()
return
self._callable(*self._callableArgs)
self._oneRunFinished.set()
def join(self)
self._oneRunFinished.wait()
self._oneRunFinished.clear()
def finish(self):
self._finishIndicator = True
self.restart()
self.join()
Example of Using the Code
def doSomething(objectToProcess):
print(str(objectToProcess[0]))
pass
changableObject = [0]
thread = ReusableThread(target = doSomething,
args = [changableObject])
changableObject[0] = 1
thread.start()
thread.join()
changableObject[0] = 2
thread.restart()
thread.join()
changableObject[0] = 3
thread.restart()
thread.join()
thread.finish()