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:

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:

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.

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.

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:

  • odoood

    Nice – had no clue what a thread was before this, the tutorials in pydocs don't say anything, though the brief tour of the library says something about "a technique for decoupling tasks which are not sequentially dependent"…

    laymen terms are nice :P