I’m using Python in a webapp (CGI for testing, FastCGI for production) that needs to send an occasional email (when a user registers or something else important happens). Since communicating with an SMTP server takes a long time, I’d like to spawn a thread for the mail function so that the rest of the app can finish up the request without waiting for the email to finish sending.
I tried using thread.start_new(func, (args)), but the Parent return‘s and exits before the sending is complete, thereby killing the sending process before it does anything useful. Is there anyway to keep the process alive long enough for the child process to finish?
Take a look at the
thread.join()method. Basically it will block your calling thread until the child thread has returned (thus preventing it from exiting before it should).Update:
To avoid making your main thread unresponsive to new requests you can use a while loop.
Update 2:
It also looks like
thread.start_new(func, args)is obsolete. It was updated tothread.start_new_thread(function, args[, kwargs])You can also create threads with the higher level threading package (this is the package that allows you to get theactive_count()in the previous code block):