In Python you can create threads using the thread module in Python 2.x or _thread module in Python 3. We will use the threading module to interact with it.
A thread is an operating system process with different features than a normal process:
- threads exist as a subset of a process
- threads share memory and resources
- processes have a different address space (in memory)
When would you use threading? Usually when you want a function to occur at the same time as your program. If you create server software, you want the server not only listens to one connection but to many connections. In short, threads enable programs to execute multiple tasks at once.
- Complete Python Bootcamp: Go from zero to hero in Python
- Automate the Boring Stuff with Python Programming
Let’s create a thread program. In this program we will start 10 threads which will each output their id.
import threading # Our thread class class MyThread (threading.Thread): def __init__(self,x): self.__x = x threading.Thread.__init__(self) def run (self): print str(self.__x) # Start 10 threads. for x in xrange(10): MyThread(x).start()
0 1 ... 9
Threads do not have to stop if run once. Threads could be timed, where a threads functionality is repeated every x seconds.
In Python, the Timer class is a subclass of the Thread class. This means it behaves similar. We can use the timer class to create timed threads. Timers are started with the .start() method call, just like regular threads. The program below creates a thread that starts after 5 seconds.
#!/usr/bin/env python from threading import * def hello(): print "hello, world" # create thread t = Timer(10.0, hello) # start thread after 10 seconds t.start()
Repeating functionality using threads
We can execute threads endlessly like this:
#!/usr/bin/env python from threading import * import time def handleClient1(): while(True): print "Waiting for client 1..." time.sleep(5) # wait 5 seconds def handleClient2(): while(True): print "Waiting for client 2..." time.sleep(5) # wait 5 seconds # create threads t = Timer(5.0, handleClient1) t2 = Timer(3.0, handleClient2) # start threads t.start() t2.start()