Computer with multi-processing capability can execute multiple programs concurrently. This feature helps in faster programming and time-saving. Threading in the program provides the same feature for running small parts of a single program together. Here we will discuss for Python Multithreading with examples.
What is Thread?
Before we start to discuss what is multithreading, let us just take an overview of what is a thread. We can divide a big, sophisticated computer program into the smaller task. The thread is nothing but this small task. We can execute multiple threads concurrently for faster processing.
We can also say that Threads of a program are light weight process because they don’t use large memory for processing.
Each thread in the memory of the same program shares same space for data using the main thread. Thus the threads can also communicate with each other to exchange information.
The execution flow of thread is similar to the process. It has a pointer of instruction that keeps the record of which part is currently under execution.
Once we start to run a thread, it will not stop until statements are executed. But also we can interrupt the current running thread if we want. We can also switch the thread in between of execution if needed.
How to create a thread?
In Python Multithreading, to work with the thread, we have to create them first. To create a thread we have to follow two steps.
We have to import the module name threading. The threading module had a various built-in function to work with thread. After importing the threading module, we have to create the object of the thread. Once we have created the thread object, we have to call the start method to run the thread.
To create the object of the thread, we have to use the Thread method to create the thread object.
In the Thread() method, we have to pass some arguments. We have to give the name of the function of which we want to create the thread.Second is the args; it is a tuple of arguments.
import time from threading import Thread #create function for thread def Tfunc(i): print("%d sleeping 5 sec from thread\n" % i) time.sleep(5) print("\n %d finished sleeping from thread" % i) #start the thread for function for i in range(5): t1 = Thread(target=Tfunc, args=(i,)) t1.start()
In above example, we will create a simple thread example. We have given function name to the thread method. The method will print a statement after each five seconds.
0 sleeping 5 sec from thread 1 sleeping 5 sec from thread 2 sleeping 5 sec from thread 3 sleeping 5 sec from thread 4 sleeping 5 sec from thread 0 finished sleeping from thread 1 finished sleeping from thread 2 finished sleeping from thread 3 finished sleeping from thread 4 finished sleeping from thread
The output of the above code looks simple, but when we execute the code, we will understand better how the thread works. The best part of the running thread is each time it gives different output.
In Python multithreading, we have new module name Threading to work with thread. The threading module was added in Python with version 2.4. We have to import the threading module in the program to work with method available in the Threading Module.
Methods in Threading module
|run()||This method is the entry point of the thread.|
|start()||This method will start the execution of the thread. We have to create the object of thread to use the start() method.|
|join(time)||In this method we have to pass the time with the unit of seconds. The thread which calls the time() method will accede to the another thread after the time we have given.|
|isAlive()||With the object of the thread, we can call this method.It returns true if the thread is active in the execution else it gives false.|
|getName()||This method will return the name of the current thread in the execution.|
|setName()||The method will set the name of the thread of which we have the object. We have to pass the old name and new name to change it.|
|active_count()||This method returns a total number of threads which are running concurrently with the main thread.|
|current_thread()||This method gives the total number of the current thread under execution with the thread controls of the caller object.|
|enumerate()||It will include a list which contains the name of the objects that are currently active.|
Example of Threading module
import time import threading #create function for thread def Tfunc(i): print("Thread no.:%d" % (i+1)) time.sleep(5) print("%d finished sleeping from thread\n" % i) #start the thread for function for i in range(3): t1 = threading.Thread(target=Tfunc, args=(i,)) t1.start() #check thread is alive or not c=t1.isAlive() #fetch the name of thread c1=t1.getName() print('\n',c1,"is Alive:",c) #get toatal number of thread in execution count=threading.active_count() print("Total No of threads:",count)
In above example, we have only to use the methods available in the threading module.
Thread no.:1 Thread-1 is Alive: True Total No of threads: 3 Thread no.:2 Thread-2 is Alive: True Total No of threads: 4 Thread no.:3 Thread-3 is Alive: True Total No of threads: 5 0 finished sleeping from thread 1 finished sleeping from thread 2 finished sleeping from thread
Synchronization in threads
In Python multithreading programming, we can perform synchronization between thread for better execution. Synchronization in threads means making communication between threads or passing information.
We can control the flow of execution of one thread with another thread. We have following method for Synchronization in Threading module of Python.
This method creates a new lock for synchronization.
This function will force other threads to execute synchronously. We can pass the blocking argument that enables to control the thread to wait to acquire a new lock.
If we set the parameter blocking 0, then the thread returns immediately with a 0 value if the lock cannot be acquired else one if we can acquire a lock.If we set blocking to 1, the thread blocks and wait for the lock to be released.
It will release the lock when we no longer require the lock.
import threading import time # global variable x x = 0 def Tfunc(i,lock): lock.acquire() print('from thread %d' %i) lock.release() # creating a lock lock = threading.Lock() # creating threads t1 = threading.Thread(target=Tfunc, args=(1,lock,)) t2 = threading.Thread(target=Tfunc, args=(2,lock,)) # start threads t1.start() t2.start() # wait until threads finish their job t1.join() time.sleep(5) t2.join()
from thread 1 from thread 2
Multithread Priority Queue
We can use the Queue module in Python multi threading programming. We can use the queue module to hold some values under one queue object.
In module of queue, we have following method to work with threads,
|get()||It will give an item from the queue|
|put()||It adds an item to the queue.|
|qsize()||This method will return a total number of elements in the queue.|
|Empty()||If the queue is empty it will return true else false.|
|Full()||if the queue is full the method will return true else false.|
Here we will conclude the topic of Python Multithreading if any questions feel free to ask in comments below.