I have some python codes in string format (output of Blockly) that I use for to instance a custom class. Then they are executed concurrently in threads. This is a simplistic example of the code:
import threading
from time import sleep
class myFunction(object):
def __init__(self, code):
self._code = code
self._stoprequest = False
def start(self):
while not self._stoprequest:
exec code
sleep(1)
def stop(self):
self._stoprequest = True
''' other functions '''
threads = []
f1 = myFunction("print 'hello'")
f2 = myFunction("var=0\nwhile True:\n print var\n var=var+1")
f3 = myFunction("sleep(3600)")
functions=[(f1,'f1'),(f2,'f2'),(f3,'f3')]
for function in functions:
t = threading.Thread(target = function[0].start(), name=function[1])
threads.append(t)
t.start()
sleep(5)
functions[0][0].stop()
functions[1][0].stop()
functions[2][0].stop()
For function 'f1' my implementation works, due to the code executed is not an infinite loop.
But for function 'f2' and 'f3' does not work ('f3' will end after sleep)
Searching for the answer I found this question, that could work for 'sleeps' but not for infinite loops.
Is there any way to end the execution of any kind of code? I don't mind if it's killing the thread or catching an exception.