If you want your application to perform several tasks at once, you can use threads. Python can handle threads, but many developers find thread programming to be very tricky. Among other points, Peyton McCullough covers how to spawn and kill threads in this popular language.
There is more to threads than just spawning them and sending them on their way. The threading module's Thread module contains a few more methods that you should be aware of. The first two deal with naming threads. The method setName sets a thread's name, and the method getName retrieves a thread's name:
We can use the setDaemon method, too. If a True value is passed with this method and all other threads have finished executing, the Python program will exit, leaving the thread by itself:
import threading import time
class DaemonThread ( threading.Thread ):
def run ( self ):
self.setDaemon ( True ) time.sleep ( 10 )
DaemonThread().start() print 'Leaving.'
Python also contains a thread module that deals with lower level threading. The only feature I would like to point out is the start_new_thread function it contains. Using this, we can turn an ordinary function into a thread:
def thread( stuff ): print "I'm a real boy!" print stuff
There's much more to multi-threading than I explained in this article, but I will not bore you by extending the scope of this article to include everything. Moreover, as Guido van Rossum mentioned, the advantage gained by complex multi-threading in Python may be outweighed by the consequences. A small dose of common sense can eliminate much of the problems in simple multi-threading, however.
Threading is very important when dealing with computer applications, and, as I mentioned earlier, Python isn't excluded. When used properly, threads can be very beneficial and often even crucial, as I've outlined in this article.