0

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.

Community
  • 1
  • 1
JaviCru
  • 51
  • 1
  • 9
  • Why do you need to stop them? Are they preventing your program from exiting? If so, set the background threads as deamons. – g.d.d.c Feb 11 '16 at 23:57
  • It is not a daemon issue. What I want is to manage of all codes at any time, start and stop principally. – JaviCru Feb 12 '16 at 07:49

0 Answers0