Why does threading.Thread operate synchronously by blocking execution in python 2.5?

1.1k views Asked by At

I am limited to python2.5, and I thought that threading.Thread was asynchronous. I run: python t.py and the script does not return to the shell until 3 seconds have gone by, which means its blocking. Why is it blocking?

My Code:

#!/usr/bin/python
import threading,time

def doit():
  time.sleep(3)
  print "DONE"

thr = threading.Thread(target=doit, args=(), kwargs={})
thr.start() # will run "foo"
2

There are 2 answers

3
dano On BEST ANSWER

By default, threads in Python are non-daemonic. A Python application will not exit until the all non-daemon threads have completed, so in your case it won't exit until doit has finished. If you want to script to exit immediately upon reaching the end of the main thread, you need to make the thread a daemon, by setting the daemon attribute prior to starting the thread:

thr = threading.Thread(target=doit, args=(), kwargs={})
thr.daemon = True
thr.start()
0
Ethan Furman On

Threading in Python is "kind-of" asynchronous. What does this mean?

  • Only one thread can be running Python code at one time

  • threads that are Python code and CPU intensive will not benefit

Your issue seems to be that you think a Python thread should keep running after Python itself quits -- that's not how it works. If you do make a thread a daemon then when Python quits those threads just die, instantly -- no cleanup, no error recovery, just dead.

If you want to actually make a daemon process, something that keeps running in the background after the main application exits, you want to look at os.fork(). If you want to do it the easier way, you can try my daemon library, pandaemonium