How to use ThreadPoolExecutor in Python with example

In this tutorial, We will discuss ThreadPoolExecutor in Python.

How to use ThreadPoolExecutor in Python

ThreadPoolExecutor is a subclass of executor first time introduced in Python version 3.2. It uses pools of threads to execute calls asynchronously.ThreadPoolExecutor provides a simple high-level interface for the execution of asynchronous I/O bound tasks.

Why ThreadPoolExecutor?
Using the ThreadPoolExecutor has the following advantages:-
1. ThreadPoolExecutor simply provides an abstraction around multiple threads.
2. It performs the tasks assigned to it concurrently.
3. Using the threads in our application can improve the speed of our application if we use it in the right context etc.

How to create ThreadPoolExecutor?

The syntax of the creation of ThreadPoolExecutor is :
object=ThreadPoolExecutor(max_workers=2)
Where max_workers is the number of concurrent threads that can process any task submitted to it.
After that, To create the threads in our ThreadPoolExecutor, we call the submit function that simply takes a function as its primary parameter.
object.submit(myFunc())

Example :

In the example, we have imported ThreadpoolExecutor from concurrent.futures and threading.
We have created an instance of ThreadpoolExecutor and assign it a task called myTask together.
Our task is simply to print the sum of all even numbers from 0 to 100.
threading.current_thread() function tells us which thread has performed our tasks.

from concurrent.futures import ThreadPoolExecutor
import threading #importing threading module


print("Here, Our task is executing.....")
def myTask():
    ''' function that prints sum of all even numbers from 0 to 100 '''
    sumation = 0
    x = 0
    for x in range(0,100,2):
        sumation = sumation + x
    print(f' I : {format(sumation)}')
    print(f' Task is executed {format(threading.current_thread())}')

def main():
    ''' main function instantiates an instance of ThreadPoolExecutor and assign the desired task to it'''
    ob = ThreadPoolExecutor(max_workers=4)
    task = ob.submit(myTask())

if __name__ == '__main__':
    main()

Output :

Here, Our task is executing.....
I : 2450
Task is executed <_MainThread(MainThread, started 11132)>

I hope, this tutorial will help you to understand ThreadPoolExecutor.

Leave a Reply

Your email address will not be published. Required fields are marked *