"
This article is part of in the series
Last Updated: Thursday 9th May 2013

Introduction to Python threads

What are threads? Simply put, try to imagine them as running several programs concurrently, in a single process. When you create one or more threads in your program, they get executed simultaneously, independent of each other, and most importantly, they can share information among them without any extra difficulty.

These features make threads lightweight and handy in situations like network programming, when you try to ping (send network packets or requests) hundreds of workstations and you don't want to ping them one after another! Since network replies may come after a significant amount of delay, the program will be extremely slow if you don't ping many workstations concurrently. This article will show you how to create a thread in Python, and how to use them in general.

Create a Thread in Python

Threading in Python is easy. First thing you need to do is to import Thread using the following code:

[python]
from threading import Thread
[/python]

To create a thread in Python you'll want to make your class work as a thread. For this, you should subclass your class from the Thread class:

[python]
class MyThread(Thread):
def __init__(self):
pass
[/python]

Now, our MyThread class is a child class of the Thread class. We then define a run method in our class. This function will be executed when we call the start method of any object in our MyThread class.

The code of the complete class is shown below. We use the sleep function to make the thread "sleep" (prevent it from executing for a random amount of time). If we don't do this, the code will be executed so quickly that we will not be able to notice any worthwhile changes.

[python]
class MyThread(Thread):
def __init__(self, val):
''' Constructor. '''

Thread.__init__(self)
self.val = val

def run(self):
for i in range(1, self.val):
print('Value %d in thread %s' % (i, self.getName()))

# Sleep for random time between 1 ~ 3 second
secondsToSleep = randint(1, 5)
print('%s sleeping fo %d seconds...' % (self.getName(), secondsToSleep))
time.sleep(secondsToSleep)
[/python]

To create the thread, the next step is to create some objects (two in this example) of our thread-supported class. We call the start method of each object – this in turn executes the run method of each object.

[python]
# Run following code when the program starts
if __name__ == '__main__':
# Declare objects of MyThread class
myThreadOb1 = MyThread(4)
myThreadOb1.setName('Thread 1')

myThreadOb2 = MyThread(4)
myThreadOb2.setName('Thread 2')

# Start running the threads!
myThreadOb1.start()
myThreadOb2.start()

# Wait for the threads to finish...
myThreadOb1.join()
myThreadOb2.join()

print('Main Terminating...')
[/python]

That's it! Note that we need to call the join method of each object – otherwise, the program will terminate before the threads complete their execution.

The complete version of the program looks like this:

[python]
from threading import Thread
from random import randint
import time

class MyThread(Thread):

def __init__(self, val):
''' Constructor. '''
Thread.__init__(self)
self.val = val

def run(self):
for i in range(1, self.val):
print('Value %d in thread %s' % (i, self.getName()))

# Sleep for random time between 1 ~ 3 second
secondsToSleep = randint(1, 5)
print('%s sleeping fo %d seconds...' % (self.getName(), secondsToSleep))
time.sleep(secondsToSleep)

# Run following code when the program starts
if __name__ == '__main__':
# Declare objects of MyThread class
myThreadOb1 = MyThread(4)
myThreadOb1.setName('Thread 1')

myThreadOb2 = MyThread(4)
myThreadOb2.setName('Thread 2')

# Start running the threads!
myThreadOb1.start()
myThreadOb2.start()

# Wait for the threads to finish...
myThreadOb1.join()
myThreadOb2.join()

print('Main Terminating...')
[/python]