title: Escaping arbitrary blocks of code
body: <p>My script accepts arbitrary-length and -content strings of Python code, then runs them inside exec() statements. If the time to run the arbitrary code passes over some predetermined limit, then the exec() statement needs to exit and a boolean flag needs to be set to indicate that a premature exit has occurred.</p>
  
  <p>How can this be accomplished?</p>
  
  <h3>Additional information</h3>
  
  <p>These pieces of code will be running in parallel in numerous threads (or at least as parallel as you can get with the GIL).</p>
  
  <p>If there is an alternative method in another language, I am willing to try it out.</p>
  
  <p>I plan on cleaning the code to prevent access to anything that might accidentally damage my system (file and system access, import statements, nested calls to exec() or eval(), etc.).</p>
  
  <h3>Options I've considered</h3>
  
  <ol>
  <li>Since the exec() statements are running in threads, use a poison pill to kill the thread. Unfortunately, I've read that poison pills do not work for all cases.</li>
  <li>Running the exec() statements inside processes, then using <code>process.terminate()</code> to kill everything. But I'm running on Windows and I've read that process creation can be expensive. It also complicates communication with the code that's managing all of this.</li>
  <li>Allowing only pre-written functions inside the exec() statements and having those functions periodically check for an exit flag then perform clean-up as necessary. This is complicated, time-consuming, and there are too many corner-cases to consider; I am looking for a simpler solution.</li>
  </ol>
  
  <p>I know this is a bit of an oddball question that deserves a "Why would you ever want to allow arbitrary code to run in an exec() statement?" type of response. I'm trying my hand at a bit of self-evolving code. This is my major stumbling block at the moment: if you allow your code to do almost anything, then it can potentially hang forever. How do you regain control and stop it when it does?</p>