Python Threading – In this tutorial, you will learn python threading example, multithreading in python with example, daemon thread python, non-daemon thread python with program examples.
THREADING
- Thread is a path of the execution within a process.
TASK BASED TYPES
- Single Threading
- Multithreading
DIFFERENCE BETWEEN SINGLE THREAD AND MULTIPLE THREADS
S.N | SINGLE THREAD | MULTITHREADING |
1. | Performs single task | Performs multitasking. Doing more than one job at the same time |
2. | It consists of only one thread | It consists of several threads |
3. | It is used for experimental purpose | It is used for larger tasks. |
LIFE CYCLE OF THREADS
- Thread has five life cycles. It always lives in any of the states.
- New born state (New state)
- Runnable state
- Running state (execution state)
- Blocked state
- Dead state (End state).
BUILT-IN METHODS
1. start()
- This is runnable state (waiting for the execution)
- This is method is used to start the thread
- Return type : None
2. threading.currentThread().getName()
- This method is used to display the name of currently executing or running thread
- Return type : Str
Thread Creation
- Thread is created by using the built-in super class Thread Thread(name=<user-defined-name, target=<function-name>, )
- It is a built-in class which is used to create a new thread object
- It takes two or more arguments
- First argument is the name of the thread. It can be any name set by the user. It is optional argument
- Second argument is target which is used to call the user defined function
Required Module
I. EXAMPLE OF SINGLE THREAD
Tools used : VSC Editor
Platform OS : Windows 10
Language : Python 3
1. SOURCE CODE
from threading import *
# user defined function
def welcome():
print(“Hello World…”)
print(“——————————————“)
print(“\tSingle Thread”)
print(“——————————————“)
# creating object for single thread
t1=Thread(target=welcome, name=”Thread 1″)
# start the thread by calling start method
t1.start()
2. OUTPUT
Pictorial Representation
MULTITHREADING
- Process of executing more than one thread at the same time (Execution of multiple threads simultaneously)
- It is important to note that, we can’t predict which thread will run first.
- It is important to note that, the main or current thread can randomly start any thread from the list of threads.
II. EXAMPLE OF MULTITHREADING
(Asynchronous Processes)
Tools used : VSC Editor
Platform OS : Windows 10
Language : Python 3
1. SOURCE CODE
from threading import *
# user defined function 1
def m1():
for i in range(3):
print(“Good Morning…”)
# user defined function 2
def m2():
for i in range(3):
print(“Good Evening…”)
# user defined function 3
def m3():
for i in range(3):
print(“Good Night…”)
print(“——————————————“)
print(“\tMultithreading”)
print(“——————————————“)
# creating objects for multiple threads
t1=Thread(target=m1,name=”Morning”)
t2=Thread(target=m2,name=”Evening”)
t3=Thread(target=m3,name=”Night”)
# start the threads by calling start method
t1.start()
t2.start()
t3.start()
Pictorial Representation
2. OUTPUT
III. EXAMPLE OF MULTITHREADING
(Synchronous Processes using join() method)
Tools used : VSC Editor
Platform OS : Windows 10
Language : Python 3
Existing Issues
- By default, the threads are running parallel in multithreading
- In the execution of multithreading using asynchronous methods, the threads will be running in parallel. That’s why the output came differently in the previous example.
- So in order to execute threads one by one (sequential order) during the multithreading, the join method will be used.
1. SOURCE CODE
from threading import *
# user defined function 1
def m1():
for i in range(3):
print(“Good Morning…”)
# user defined function 2
def m2():
for i in range(3):
print(“Good Evening…”)
# user defined function 3
def m3():
for i in range(3):
print(“Good Night…”)
print(“——————————————“)
print(“\tMultithreading”)
print(“——————————————“)
# creating objects for multiple threads
t1=Thread(target=m1,name=”Morning”)
t2=Thread(target=m2,name=”Evening”)
t3=Thread(target=m3,name=”Night”)
# start thread 1
t1.start()
# wait until thread 1 is finished (main and sub threads t2, t3 should wait)
t1.join()
# start thread 2 after thread 1
t2.start()
# wait until thread 2 is finished (main and sub threads t1, t3 should wait)
t2.join()
# start thread 3 after thread 2
t3.start()
# wait until thread 3 is finished (main and sub threads t1, t2 should wait)
t3.join()
# end of the main thread
print(“End of the main thread…”)
2. OUTPUT
IV. DETECTION OF CURRENTLY EXECUTING THREAD
Tools used : VSC Editor
Platform OS : Windows 10
Language : Python 3
1. SOURCE CODE
from threading import *
import threading
# user defined function 1
def m1():
tname=threading.currentThread().getName()
print(“Current Thread\t: “,tname)
print(“Good Morning…”)
# user defined function 2
def m2():
tname=threading.currentThread().getName()
print(“Current Thread\t: “,tname)
print(“Good Evening…”)
# user defined function 3
def m3():
tname=threading.currentThread().getName()
print(“Current Thread\t: “,tname)
print(“Good Night…”)
# main thread
print(“——————————————-“)
print(“\tFinding Current Thread – Multithreading”)
print(“——————————————-“)
# creating objects for multiple threads
t1=Thread(target=m1,name=”Morning”)
t2=Thread(target=m2,name=”Evening”)
t3=Thread(target=m3,name=”Night”)
# start threads
t1.start()
t2.start()
t3.start()
# end of the main thread
print(“End of the main thread…”)
2. OUTPUT
GENERAL TYPES OF THREAD
- Like java, python supports two types of threads. They are
- Daemon thread
- Non daemon thread (User Thread)
1. Daemon Thread
- If a thread is running in background mode, then it is called as daemon thread
- It has low priority level than user thread
- This is created by adding the boolean value to the daemon argument of the Thread class.
2. Non Daemon Thread
- If a thread is running in foreground mode, then it is called as non daemon thread (user thread)
- It has high priority level than daemon thread
- This is created by the thread class.
DIFFERENCE BETWEEN DAEMON THREAD AND NON DAEMON THREAD
S.N | DAEMON THREAD | NON DAEMON THREAD |
1. | It is always runs in background mode | It is always runs in foreground mode |
2. | Main program does not wait for daemon thread to finish its task | Here main program waits for user threads have to terminate |
3. | It has low priority | It has high priority |
4. | It is not used for important tasks. It is generally used for some background tasks which are not important | Any important task is done by the user thread. |
5. | It is created by the Python Virtual Machine (PVM) | It is created by the application or program. |
6. | If all the threads have finished their execution, the PVM will force the daemon threads to finish their execution. | PVM won’t force the user threads for termination. So it waits for user threads to terminate themselves. |
I. EXAMPLE OF DAEMON THREAD
Tools used : VSC Editor
Platform OS ;: Windows 10
Language : Python 3
1. SOURCE CODE
from threading import *
from time import sleep
# user defined function 1
def m1():
for i in range(3):
print(“Good Morning…”)
sleep(2)
# user defined function 2
def m2():
for i in range(3):
print(“Good Evening…”)
# user defined function 3
def m3():
for i in range(3):
print(“Good Night…”)
print(“————————————————“)
print(“\tDaemon Thread”)
print(“————————————————“)
# creating objects for multiple threads
# convert thread t1 to daemon thread by setting the boolean true to the daemon argument of thread class
t1=Thread(target=m1,name=”Morning”, daemon=True)
# non daemon threads
t2=Thread(target=m2,name=”Evening”)
t3=Thread(target=m3,name=”Night”)
# start the thread by calling start method
t1.start()
t2.start()
t3.start()
2. OUTPUT
NOTE
- In the above output screenshot, the daemon thread t1 Good Morning is still running in the background mode.
- Even Though all threads (including main thread) are terminated, the daemon thread is still alive and running in the background.
II. EXAMPLE OF NON DAEMON THREAD
Tools used : VSC Editor
Platform OS : Windows 10
Language : Python 3
1. SOURCE CODE
from threading import *
from time import sleep
# user defined function 1
def m1():
for i in range(3):
print(“Good Morning…”)
sleep(2)
# user defined function 2
def m2():
for i in range(3):
print(“Good Evening…”)
# user defined function 3
def m3():
for i in range(3):
print(“Good Night…”)
print(“——————————————-“)
print(“\tNon Daemon Thread(User Threads)”)
print(“——————————————-“)
# creating objects for multiple threads
# Non Daemon Threads
t1=Thread(target=m1,name=”Morning”)
t2=Thread(target=m2,name=”Evening”)
t3=Thread(target=m3,name=”Night”)
# start the threads by calling start method
t1.start()
t2.start()
t3.start()
2. OUTPUT
MORE TUTORIALS
-
How to convert Word to Number in Bash Script
FacebookTweetPinLinkedInEmailShares0SharePrint In this bash tutorial, you will get convert word to number in bash script with examples.This is implemented using for loop, tr command, switch case in shell…
-
How to Count Word Frequency in Bash Script
FacebookTweetPinLinkedInEmailShares0SharePrint In this bash tutorial, you will get the program about how to count word frequency in bash script. This is done by using for loop,…
-
Bash Script – How to convert Number to Words
FacebookTweetPinLinkedInEmailShares0SharePrint In this tutorial, you will see how to convert numbers to words using bash script. This shell script can be done with the help of switch case…