I have created a daemon thread which will be independently running once it is initiated with the main Object. I can push various functions that I want it to run through its stack. BUT I never want the daemon thread to have more than 2 functions in the stack (design choice for the project I'm building). So if a method called run_this_function is running in this thread and the main object pushes that function to the stack again, then I want to stop run_this_function midway and then restart the new function pushed to the thread.
My question is whether there is any way to stop a sequence of statements once they have been initiated.
import threading
import time
class myThread(object):
"""
The run() method will be started and it will run in the background
until the application exits.
"""
def __init__(self, interval=1):
self.interval = interval
self.thread_stack = []
thread = threading.Thread(target=self.run, args=())
thread.daemon = True
thread.start()
def run(self):
# Method that runs forever
lock = threading.Lock()
while True:
if self.thread_stack:
lock.acquire()
try:
# if a method is already running on this thread, end it.
new_function = thread_stack.pop()
finally:
lock.release()
# run new function
else:
time.sleep(self.interval)
def some_function(self):
#do something
#do something
#do something else
#do one more thing
The above code is what I written so far. I would create a myThread object and push methods I want to run onto thread_stack. So if I had a function (say some_function) already running, how can I stop it midway like after the first 2 execution statements. Am I forced to have if statements for every line?
Also, feel free to comment/critique my use of threading. I'm still very new to it. Thanks! :)