Python MultiThreading Tutorial

This article is a tutorial on the use of Multithreading in Python.

Once you’ve graduated from simple programs and begin some large scale, resource intensive program, you’ll find multi-threading to be a blessing. It’s use isn’t restricted to resource intensive programs though, it can be used almost anywhere (with the correct implementation).


What is MultiThreading in Python?

Simply put, multithreading allows you to have multiple parts of your code running at the same time. Normally your code executes sequentially (line by line) on a single thread. The act of breaking your program into smaller pieces and having each part run on a separate thread is called multithreading.

Fair warning, multithreading is not for absolute beginners. Unless you have a strong grasp over the basics, you should not be attempting multithreading. The more complicated the program, the harder it is to split it into smaller pieces and manage have each section run in sync with the others. Being able to identify where and when to apply multithreading is an important skill you’ll have to learn.


What is a Thread?

By now we’ve mentioned the word “thread ” several times. A thread is like a “virtual” core. For the purpose of this article, you need to maintain this line of thinking. Think of each thread as a separate processing unit that can execute a program. And adding more threads into your program gives you more processing units to work with.

We’ll be using the threading” library in order to create and manage threads. The threading library comes with the Python standard library so you don’t have to install it separately or anything.

Here’s a little diagram we came up with to help you understand threads and multithreading. It’s a very simplified version, but it explains the basic principle behind multithreading. Each circle represents a thread and each rectangle represents a task that will take a minute to perform..