Intro to Threading in Python [Understand With Examples]

122

Threading in Python allows processors to run multiple program parts concurrently by utilizing the resources properly. The concept of threading increases the execution speed of a program. Python Threading is used mainly for Input/Output bound tasks, i.e., The tasks which spend more time on Input/Output when compared to processing (or) computing.

The advantage of threading can be known better when we compare a single-thread Python program with a multi-threaded program.

Also ReadUnderstanding How Print Statements in Python Work

Intro to Threading in Python [Understand With Examples]

threading in python

Also ReadHow to Create a Neural Network in Python

Single Threaded Python Program

The below code is a simple single-threaded program-

Code

# import necessary packages
import time

# function
def executeTask():
print('Task Execution started')
time.sleep(2)
print('Execution completed')

program_startTime=time.perf_counter()

# execute 3 tasks
executeTask()
executeTask()
executeTask()

program_endTime=time.perf_counter()

print(f'Time Taken to complete all tasks : {program_endTime-program_startTime:0.3f} seconds')

Output

Task Execution started
Execution completed
Task Execution started
Execution completed
Task Execution started
Execution completed

Time Taken to complete all tasks: 6.030 seconds

Also ReadOr Operator in Python

Explanation

  • Imported time library to use sleep() and perf_counter() methods.
  • The function executeTask() is defined in such a way that it executes a task with a sleep time of 2 seconds.
  • The sleep () method makes the CPU idle for specified seconds.
  • time.perf_counter() is used to note the program execution start time and end time to find the
  • total execution time, i.e., end time – start time.
  • We called the function executeTask 3 times, i.e., to execute 3 tasks.

As per the program, the execution of the task1 starts and sleeps for 2 seconds, then it completes the task execution, and the execution of the second task starts and then sleeps for 2 seconds and finishes its execution, and the same repeats for task 3.

single threading in python

Here resource utilization is minimal because no tasks are running concurrently. The sleep time between 2 tasks is not utilized by other tasks/processes. So to increase execution speed and resource utilization Threading concept comes into the picture.

Also ReadNatural Language Processing in Python: Techniques

Multi Threaded Program in Python

To implement the threading concept in python, import the Thread class from the threading module. To create the thread in python, use the Thread function that accepts two parameters target, which specifies the function, and other parameter args of type tuple, which specifies arguments.

Below is the syntax to create a thread

Thread1 = Thread(target=functionName, args=(arg1,arg2,..))

There are two methods used in multithreading programs. They are:

  • Start() – The start() method helps to start the thread’s execution.
  • Join() – The join() method allows the main thread to wait for the second/other thread to complete before it is terminated.

Also ReadPython Reserved Words List With Definitions and Examples

Let’s look into a simple multi threaded python program with no arguments –

Code

# import necessary packages
import time
from threading import Thread

# function
def executeTask():
print('Task Execution started')
time.sleep(2)
print('Execution completed')

program_startTime=time.perf_counter()

# create three threads
thread1 = Thread(target=executeTask)
thread2 = Thread(target=executeTask)
thread3 = Thread(target=executeTask)

# start threads
thread1.start()
thread2.start()
thread3.start()

# wait for threads to complete
thread1.join()
thread2.join()
thread3.join()

program_endTime=time.perf_counter()

print(f'Time Taken to complete all tasks : {program_endTime-program_startTime:0.3f} seconds')

Output

Task Execution started
Task Execution started
Task Execution started
Execution completed
Execution completed
Execution completed
Time Taken to complete all tasks: 2.023 seconds

Also ReadHow to Fix Invalid Syntax Error in Python

Explanation

Imported time library to use sleep(), perf_counter() methods, and Thread class to create Threads.

  • The function executeTask() is defined in such a way that it executes a task with a sleep time of 2 seconds.
  • sleep() method makes the CPU idle for specified seconds.
  • time.perf_counter() is used to note the program execution start time and end time to find the total execution time, i.e., end time – start time.
  • I created 3 threads using the Thread() method.
  • The start() method is used to start the execution of threads.
  • The join() method allows the main thread to wait for the other threads to complete.

Below is the pictorial view of the execution of three threads per the above program.

multi threading in python

Also ReadHow to Fix Unexpected EOF While Parsing Error In Python

The difference between single-threaded and multithreaded programs is that all three threads/tasks will run concurrently in the multithreaded program.

We can see from the output of the result the execution time is just 2.023 seconds instead of 6 sec as per the single-threaded program because of higher resource utilization.

During the sleep time of a thread, The CPU won’t wait for the current thread to complete its execution. It processes the other threads/tasks.

When the program starts its execution, the interpreter will create the main thread, and the three threads/tasks will be created from the program.

Also ReadHow To Copy List in Python

Below is the multithreaded program by passing arguments while threading creation.

Code

# import necessary packages
import time
from threading import Thread

# function
def executeTask(number):
    print(f'Task {number} Execution started')
    time.sleep(2)
    print(f'Task {number} Execution completed')
    
program_startTime=time.perf_counter()
# list which stores all created threads
threads=[]
# create and start three threads
for i in range(1,4):
    thread = Thread(target=executeTask,args=(i,))
    threads.append(thread)
    thread.start()

for thread in threads:
    thread.join()

program_endTime=time.perf_counter()

print(f'Time Taken to complete all tasks : {program_endTime-program_startTime:0.3f} seconds')

Output

Task 1 Execution started
Task 2 Execution started
Task 3 Execution started
Task 1 Execution completed
Task 2 Execution completed
Task 3 Execution completed

Time Taken to complete all tasks: 2.024 seconds

Also Read10 Best Programming Apps To Learn Python

There are only a few differences from the previous code, i.e., a multithreaded program with no arguments, to the above code, i.e., a multithreaded program with arguments.

  • Defined executeTask() method with an argument.
  • Passed a tuple to args argument while creating a Thread.

Note: The order of executing tasks/threads is not fixed. Here all the tasks are executed in order as per the input, but it won’t always happen.

Other Python tutorials: