4 Simple Examples for Python Threading in 2022

Python has an easy interface to use the threading module. Threading allows us to run multiple programs concurrently. There are many methods to run threads. I shared the top four methods with examples here to understand the Python threading concept easily.

Example 1: Using threading Module Directly

In this example, we import the threading module and call the Thread class of the module to start the thread.

Arguments

The Thread() class needs two arguments to be passed in order to initialize a thread.

  • target – It is used to call the function we want to execute
  • args – we need to pass the arguments to the function we need to execute

Below, I shared a simple program to understand the threading concept. The program will call the function 10 times and each function will print the message after a time delay.

Even though we call the function in order, the output order is not as same as the order of the execution.

Output

Example 2: Multithreading

Python threading module is widely used for multithreading purposes. We can understand the multithreading concept better with an easy example. In the below example, I created a program to send an HTTP request to a URL and print the status code.

Here we create a list to store each thread and finally call the join() method in order for the thread to complete the work. If you don’t call the join() method, the program will be executed but it won’t wait for the threads to complete their tasks. So, the program will be terminated before executing all the threads.

Output

Example 3: Python Multithreading with Limit

By default, Python doesn’t set any limit for thread limit. We have to set it to avoid program crashing due to high CPU load. We can set the thread limit by using ThreadPoolExecutor class.

For example, if we set the concurrent threads limit to 10 and you initiate 100 threads at a time, Python will process them using the queue. So, the first 10 threads will do the task and once it is complete, the next batch will be executed.

Output

In the above example, we set the thread limit to 5. So, at any time, only 5 threads can be run concurrently. Check the time of execution to understand the threading better.

Example 4: Multithreading Using Queue

This example is an extension of the example 2. Here, we use Queue module to collect the data from the threads we run.

This method is very useful if you would like to run threads that return values after execution.

Output

Conclusion

Among the above four methods, I suggest people the 3rd method that uses ThreadPoolExecutor to limit the threads. This method is easy to implement and works very faster and CPU optimized.

References: