Skip to content

Multi-threading programming in Python





Python – Multi Threading


As we read earlier about Encapsulation and Abstraction in python and we finished the Python – Advanced OOP topic. Now we will study about a new concept i.e. Multi-Threading Programming in Python. These topic are a little bit confusion type but also interesting so study them carefully.






What is a Process in Python ?


In Python programming, Process is Big program that can directly dispatch to CPU ( Central Processing Unit ).

Two or more processes do not share memory directly.


Multi-threading programming in Python




What is a Thread in Python ?


In Python programming, Thread is a Small program that can directly dispatch to CPU ( Central Processing Unit ). Two or more threads can share memory directly with each other. A thread has a starting point, an execution sequence, and a result.





What is Multi threading in Python ?


In Python programming, Multithreading is defined as the ability of a process to execute multiple threads parallely or concurrently is called Multi-threading. Python multi-threading can expressively improve the performance of any program.





What are the Modules of Multi-threading programming in Python?



  • Thread
  • Threading

By using the Threading module, a new thread of execution may be started by creating a new threading. Thread and assigning it a function to execute :

The threading module combines all the methods of the thread module and exposes few additional methods.


Example :

import threading
def function():
    print(" Hello CodifyShow ")

my_thread = threading.Thread(target=function)

In the above example, the target parameter references the function to be run. The thread will not begin execution until Start is called on the Thread Object.






How to use the Threading Module to create Threads ?



  • threading.activeCount( ) : It finds the total number of active thread objects.

  • threading.currentThread( ) : To determine the number of thread objects in the caller’s thread control.

  • threading.enumerte( ) : It will give you a complete list of thread objects that are currently active.

Apart from the above methods, threading module also presents the thread class that you can try for implementing threads.

The thread class has following methods are : 


CLASS METHODSDETAIL
run( )It is the entry point function for any thread.
start( )The start( ) method triggers a thread when the run method gets called.
join([time])The join( ) method enables a program to wait for threads to terminate.
isAlive( )The isAlive( ) method verifies an active thread.
getName( )The getName( ) method retrieves the name of a thread.
setName( )The setName( ) method updates the name of a thread.





What are the Types of Thread in Python?



Basically there are are two types of thread are :

  • Daemon : A daemon thread runs without blocking the main program from exiting and when main program exits, associated daemon threads are killed too.
  • Non Daemon : A non-daemon thread blocks the main program to exit if they are not dead.

NOTE : By Default all threads are Non-Daemon.






How to starting a thread using threading module ?



We have a simple program where we are creating two threads and start the threads.


Example :

import threading

def func():
    print("Starting of thread :",threading.current_thread().getName())

def func1():
    print("Starting of thread :",threading.current_thread().getName())

my_thread = threading.Thread(target=func)
my_thread.start()

my_thread1 = threading.Thread(target=func1)
my_thread1.start()

Output :

Starting of thread : Thread-1
Starting of thread : Thread-2





Python Multi-Threading Programming for loop



We have another simple program for python multi-threading using for loop and also used the time module in this program.


Example :

import time
import threading

def fun1():
    for i in range(15):
        print(threading.current_thread().getName(),i)
        time.sleep(.5)
        
def fun2():
    for i in range(5):
        print(threading.current_thread().getName(),i)
        time.sleep(.5)

th1=threading.Thread(target=fun1)
th2=threading.Thread(target=fun2)

th1.start()
th2.start()
th2.join()

print("Total Active Thread=",threading.active_count())

for i in range(2):
    time.sleep(.5)
    print(threading.current_thread().getName(),"Finished")

Output :

Thread-1 0
Thread-2 0
Thread-2Thread-1  11

Thread-1Thread-2  22

Thread-2Thread-1  33

Thread-1Thread-2  44

Thread-1Total Active Thread=  52

Thread-1MainThread  6Finished

Thread-1 7
MainThread Finished
Thread-1 8
Thread-1 9
Thread-1 10
Thread-1 11
Thread-1 12
Thread-1 13
Thread-1 14

The output will be slightly different each time after running the program.






Summary – Python Multi-Threading Progarmming for Beginners



I hope you find this Python Multi-Threading programming tutorial very interesting and beneficial. we want to help you and improve your Python skills.

If you like this post, then share it with your friends via social media.