- We can create a thread in python by using 3 ways:
- Creating a thread without using any class.
- Creating a thread by extending thread class.
- Creating a thread without extending thread class.
Creating a thread without using any class.
Python
from threading import *
def display():
for i in range(1,5):
print("Child Thread")
t=Thread(target=display)
t.start()
for i in range(1,5):
print("Main Thread")
Output
PowerShell
Child Thread
Main Thread
Main Thread
Main Thread
Main Thread
Child Thread
Child Thread
Child Thread
- If multiple threads present in our program, then we cannot expect execution order and hence we cannot expect exact output for the multi threaded programs. Because of this we cannot provide exact output for the above program .It is varied from machine to machine and run to run.
- The thread is a pre defined class present in threading module which can be used to create our own threads.
Creating a thread by extending thread class.
- We have to create child class for thread class. In that child class we have to override run() method with our required job. Whenever we call start() method then automatically run() method will be executed and performs our job.
Python
from threading import *
class NewThread(Thread):
def run(self):
for i in range(5):
print("Child Thread-1")
t=NewThread()
t.start()
for i in range(5):
print("Main Thread-2")
Output
PowerShell
Child Thread-1
Child Thread-1
Main Thread-2
Main Thread-2
Main Thread-2
Main Thread-2
Main Thread-2
Child Thread-1
Child Thread-1
Child Thread-1
Creating a thread without extending thread class.
Python
from threading import *
class Test:
def display(self):
for i in range(5):
print("Child Thread-1")
obj=Test()
t=Thread(target=obj.display)
t.start()
for i in range(5):
print("Main Thread-2")
Output
PowerShell
Child Thread-2
Child Thread-2
Main Thread-1
Main Thread-1
Child Thread-2
Child Thread-2
Child Thread-2
Main Thread-1
Main Thread-1
Main Thread-1
Case Study
- Justify multithreading in python can enhance performance.
Without multi threading
Python
from threading import *
import time
def doubles(numbers):
for n in numbers:
time.sleep(1)
print("Double:",2*n)
def squares(numbers):
for n in numbers:
time.sleep(1)
print("Square:",n*n)
numbers=[1,2,3,4,5,6]
begintime=time.time()
doubles(numbers)
squares(numbers)
print("The total time taken:",time.time()-begintime)
Output
PowerShell
Double: 2
Double: 4
Double: 6
Double: 8
Double: 10
Double: 12
Square: 1
Square: 4
Square: 9
Square: 16
Square: 25
Square: 36
The total time taken: 12.004874229431152
With multi threading
Python
from threading import *
import time
def doubles(numbers):
for n in numbers:
time.sleep(1)
print("Double:",2*n)
def squares(numbers):
for n in numbers:
time.sleep(1)
print("Square:",n*n)
numbers=[1,2,3,4,5,6]
begintime=time.time()
t1=Thread(target=doubles,args=(numbers,))
t2=Thread(target=squares,args=(numbers,))
t1.start()
t2.start()
t1.join()
t2.join()
print("The total time taken:",time.time()-begintime)
Output
PowerShell
Square: 1
Double: 2
Square: 4
Double: 4
Square: 9
Double: 6
Square: 16
Double: 8
Double: 10
Square: 25
Square: 36
Double: 12
The total time taken: 6.003433465957642
Daemon Threads
- The threads which are running in the background are called daemon threads. The main objective of daemon threads is to provide support for non daemon threads (like main thread). Example – garbage collector
- Whenever main thread runs with low memory, immediately PVM runs garbage collector to destroy useless objects and to provide free memory, so that main thread can continue its execution without having any memory problems.
- We can check whether thread is daemon or not by using:
- isdaemon() ⇒ Get ‘DeprecationWarning’
- daemon
Example
Python
from threading import *
print(current_thread().isDaemon())
print(current_thread().daemon)
Output
PowerShell
False
False
- We can change daemon nature by using setdaemon() method of thread class.
- We can use this method before starting of thread i.e. once thread started, we cannot change its daemon nature, otherwise we will get runtime exception.
Python
from threading import *
print(current_thread().daemon)
current_thread().setDaemon(True)
Output
PowerShell
False
RuntimeError: cannot set daemon status of active thread
- By default main thread is always non-daemon. But for the remaining threads daemon nature will be inherited from parent to child i.e. if the parent thread is daemon then child thread is also daemon and if the parent thread is non daemon then child thread is also non daemon.
Example
Python
from threading import *
def job():
print("Child Thread")
t=Thread(target=job)
print(t.daemon)
t.setDaemon(True)
print(t.daemon)
Output
PowerShell
False
True
- Main thread is always non-daemon and we cannot change its daemon nature because it is already started at the beginning only whenever the last non-daemon thread terminates automatically all daemon threads will be terminated.
Example
Python
from threading import *
import time
def job():
for i in range(10):
print("Lazy Thread")
time.sleep(2)
t=Thread(target=job)
#t.setDaemon(True)
t.start()
time.sleep(5)
print("End Of Main Thread")
Output
- If we comment line 8 then both main thread and child threads are non daemon and hence both will be executed until their completion.
PowerShell
Lazy Thread
Lazy Thread
Lazy Thread
End Of Main Thread
Lazy Thread
Lazy Thread
Lazy Thread
Lazy Thread
Lazy Thread
Lazy Thread
Lazy Thread
- If we uncomment line 8 then main thread is non-daemon and child thread is daemon.
PowerShell
Lazy Thread
Lazy Thread
Lazy Thread
End of Main Thread
Ungraded Questions
Get ready for an exhilarating evaluation of your understanding! Brace yourself as we dive into the upcoming assessment. Your active participation is key, so make sure to attend and demonstrate your knowledge. Let’s embark on this exciting learning journey together!