0

I'm writing a program in which I want to evaluate a piece of code asynchronously. I want it to be isolated from the main thread so that it can raise an error, enter an infinite loop, or just about anything else without disrupting the main program. I was hoping to use threading.Thread, but this has a major problem; I can't figure out how to stop it. I have tried Thread._stop(), but that frequently doesn't work. I end up with a thread that I can't control hogging both interpreter time and CPU power. The code in the thread doesn't open any files or do anything else that would cause problems if I hard-killed it.

Python's multiprocessing.Process.terminate() does this really well; unfortunately, initiating a process on Windows takes nearly a second, which is long enough to cause annoying delays in my GUI.

Does anyone know either a: how to kill a Python thread (I don't think I care how dirty the exit is), or b: how to speed up starting a process?

A third possibility would be a third-party library that provides an alternative method for asynchronous execution, but I've never heard of any such thing.

Matthew
  • 306
  • 4
  • 17
  • I'm not sure this is possible. Take a look at this: http://stackoverflow.com/questions/11431637/how-can-i-kill-a-thread-in-python – merlin2011 Apr 02 '14 at 02:44
  • Can you create a single worker `Process` or `Pool` at startup to avoid the delay of creating processes on demand? – Eryk Sun Apr 02 '14 at 04:58
  • @eryksun: good idea. According to the documentation, Pool does have a terminate method, which is important. However, does it have a way to start new processes to replace terminated ones, or do I have to do this manually? Consider putting this in an answer! – Matthew Apr 02 '14 at 22:16

1 Answers1

0

In my case, the best way to do this seems to be to maintain a running worker process, and send the code to it on an as-needed basis. If the process acts up, I kill it and then start a new one immediately to avoid any delay the next time.

Matthew
  • 306
  • 4
  • 17