Threading Module Crashes the App
The following simple sample code crashes Pythonista (below). Is this a known bug and, if so, is there a workaround? Thanks, Stefan
now = datetime.datetime.now()
print "%s says Hello World at time: %s" % (self.getName(), now)
for i in range(3):
t = ThreadClass()
POSIX threading is supported in iOS, so I'm not sure why threading specifically is crashing Pythonista.
Try removing the code that prints to stdout (<b>print "finished"</b>, etc.) and turn it into a loop that either sets a global variable value or just increments a variable or something. And maybe get rid of the sleeping in the thread as well. Try to make it as simple a class implementation as possible.
See if that removes the crashing. It may have less to do with threading and more to do with threaded access to resources (like stdout - which Pythonista necessarily has messed with to get it to print to the console within the app).
It's a known issue, it basically has to do with Pythonista terminating the interpreter when the script (main thread) ends. It's pretty difficult to determine whether secondary threads are still running, and if they are, it's basically impossible to stop them from outside, so even though it's <em>possible</em> to do basic multi-threading if you are <em>very</em> careful that the main thread keeps running as long as your secondary thread(s) are, I would generally advise against it, as it very easily crashes the app or causes it to hang.
The basic problem that makes this very difficult to solve is that the interpreter has to run in the same process as the app itself because iOS apps are not allowed to spawn child processes.
@omz - Thank you for the clarification!
@stefan - Based on what omz said, a simple time.sleep(13) after your for loop at the end would allow the main thread to complete after all the secondary threads completed (if you still wanted to play with it).
An alternative would be a loop that sleeps a bit and checks the status of all your thread objects with http://docs.python.org/library/threading.html#threading.Thread.is_alive
Just join all your threads before you end the script:
threads = [ThreadClass() for i in range(3)]
for t in threads:
for t in threads: