----------------------------------------------
Python Multithreading
----------------------------------------------
Multitasking:
---------------
-computer execute more than one program or task simultaneously or concurrently.
Types of Multitasking:
--------------------------
1. Process based Multitasking
2. Thread based Multitasking
1. Process based Multitasking:
--------------------------------------
-Each task is a separate independent process
Example for OS Level:
--------------------------
a) Typing a Python Program in the editor
b) Listening audio songs from the same system
c) Downloading new songs from the internet
2. Thread based Multitasking:
--------------------------------------
-Each task is an independent part of the same program
Ex:
a) car games
b) Access Internet
c) User work with word(Typing,check grammar and print)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
thread :
--------
-A thread is a sequence of such instructions within a program that can be
executed independently of other code.
-A thread is simply a subset of a process
Multithreading
------------------
-Multithreading is defined as the ability of a processor to execute
multiple threads concurrently.
-Multithreading is the ability of a program or an operating system process
to manage its use by more than one user at a time and to even manage
multiple requests by the same user without having to have
multiple copies of the programming running in the computer.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Thread Methods:
--------------------
1. start():start the thread activity
2. run() :thread activity
3. join() :wait until the thread terminates
4. getName() : get thread Name
5. setName() : set thread Name
6. isAlive() : checks whether a thread is still executing
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# creating thread in 3 ways
1) Creating a Thread without using any class
2) Creating a Thread by extending Thread class
3) Creating a Thread without extending Thread class
----------------------------------------------------
1) Creating a Thread without using any class
-----------------------------------------------------
#Program 1: Creating a Thread without using any class
#Method 1
from threading import *
def display():
for i in range(1,5):
print(i," Thread")
#creation of thread object to execute display
t1=Thread(target=display)
t1.start()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Program 2: Creating a Thread without using any class
#Method 2
import threading
def display():
for i in range(1,5):
print(i," Thread")
#creation of thread object to execute display
t1=threading.Thread(target=display)
t1.start()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
------------------------------------------------------
2) Creating a Thread by extending Thread class
-------------------------------------------------------
#Program 1 : Creating a Thread by extending Thread class
#Method 1
from threading import *
class MyThread(Thread):
def run(self):
for i in range(1,5):
print(i," Thread")
#creation of thread object to execute display
t1=MyThread()
t1.start()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Program 2 : Creating a Thread by extending Thread class
#Method 2
import threading
class MyThread(threading.Thread):
def run(self):
for i in range(1,5):
print(i," Thread")
#creation of thread object to execute display
t1=MyThread()
t1.start()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-----------------------------------------------------------
3) Creating a Thread without extending Thread class
-------------------------------------------------------------
#Program 1 : Creating a Thread without extending Thread class
#Method 1:
from threading import *
class one:
def display(self):
for i in range(1,5):
print(i," Thread")
#creation of class object
obj=one()
t1=Thread(target=obj.display)
t1.start()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Program 2 : Creating a Thread without extending Thread class
#Method 2:
import threading
class one:
def display(self):
for i in range(1,5):
print(i," Thread")
#creation of class object
obj=one()
t1=threading.Thread(target=obj.display)
t1.start()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
------------------------------
Using Thread Methods
-----------------------------
#Program 1: using Thread Methods
from threading import *
def display():
print("welcome")
#creation of thread object to execute display
t1=Thread(target=display)
t1.start()
print("Current Thread :",current_thread())
print("Current Thread Name:",current_thread().name)
print("Thread Name :",t1.getName())
t1.setName("jahab")
print("Thread Name ",t1.getName())
print("Identification No :",t1.ident)
print("Alive or Not :",t1.isAlive())
print("Count :",active_count())
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Program 2: Example Program for Multithreading(single thread)
#Method 1:
from threading import *
import time
def msg1():
time.sleep(0.5)
print("Welcome")
print("Current Thread ",current_thread().getName())
try:
t1 = Thread(target=msg1)
# starting thread 1
t1.start()
except:
print ("Error: unable to start thread")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Program 3: Example Program for Multithreading(single thread)
#Method 2:
import threading
import time
def msg1(tname,delay):
time.sleep(delay)
print("Welcome to ",tname)
try:
t1 = threading.Thread(target=msg1, args=("Thread-1",5))
# starting thread 1
t1.start()
except:
print ("Error: unable to start thread")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Program 4: Example Program for Multithreading
import threading
import time
def msg1(tname,delay):
time.sleep(delay)
print("Welcome to ",tname)
def msg2(tname,delay):
time.sleep(delay)
print("Welcome to ",tname)
try:
t1 = threading.Thread(target=msg1, args=("Thread-1",5))
t2 = threading.Thread(target=msg2, args=("Thread-2",3))
# starting thread 1
t1.start()
print(threading.current_thread())
print(t1.getName())
t1.setName("jahab")
print(t1.isAlive())
# starting thread 2
t2.start()
except:
print ("Error: unable to start thread")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Program 5: Example Program for Multithreading
import threading
import time
def msg1(tname,delay):
for i in range(1,6):
time.sleep(delay)
print("Welcome to ",tname)
def msg2(tname,delay):
for i in range(1,6):
time.sleep(delay)
print("Welcome to ",tname)
try:
t1 = threading.Thread(target=msg1, args=("Thread-1",5))
t2 = threading.Thread(target=msg2, args=("Thread-2",3))
# starting thread 1
t1.start()
# starting thread 2
t2.start()
except:
print ("Error: unable to start thread")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Program 6: Example Program for Multithreading using join method
import threading
import time
def msg1(tname,delay):
for i in range(1,5):
time.sleep(delay)
print("Welcome to ",tname)
def msg2(tname,delay):
for i in range(1,5):
time.sleep(delay)
print("Welcome to ",tname)
try:
t1 = threading.Thread(target=msg1, args=("Thread-1",5))
t2 = threading.Thread(target=msg2, args=("Thread-2",3))
# starting thread 1
t1.start()
# wait until thread 1 is completely executed
t1.join()
# starting thread 2
t2.start()
# wait until thread 2 is completely executed
t2.join()
# both threads completely executed
print("Done!")
except:
print ("Error: unable to start thread")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
------------------------------------
Daemon Thread
-------------------------------------
-The Main purpose is to provide support for non-daemon threads(main thread)
Ex: Garbage Collector
Note:
------
-Once thread started we cannot change its Daemon nature
-Default thread Nature : Non-Daemon
-Whenever last Non-Daemon thread terminates automatically all Daemon threads will be
terminated, we are not required to terminate explicitly
-supporting jobs can be implemented by Daemon threads
-Main Jobs can be implemented by Non Daemon threads
-The entire Python program exits when only daemon threads are left.
Ex:
1)car game
cars--->Non Daemon
background Sceneries--->Daemon
2) Cinema Shooting
Hero,Heroines--->Non-Daemon
Maku up -->Daemon
Methods:
---------
1) isDaemon()
2) setDaemon(True)
3) setDaemon(False)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#Program 1 : Example for Daemon Thread
from threading import *
import time
def job1():
for i in range(10):
print("Job1")
time.sleep(2)
t1=Thread(target=job1)
print(t1.isDaemon())
t1.setDaemon(True)
print(t1.isDaemon())
t1.start()
time.sleep(10)
print("End of Main Thread")
------------------------------------------------
#Program 2 : Example for Daemon Thread
import threading
import time
def print_work_a():
print('Starting of thread :', threading.currentThread().name)
#time.sleep(2)
print('Finishing of thread :', threading.currentThread().name)
def print_work_b():
print('Starting of thread :', threading.currentThread().name)
print('Finishing of thread :', threading.currentThread().name)
a = threading.Thread(target=print_work_a, name='Thread-a', daemon=True)
#a = threading.Thread(target=print_work_a, name='Thread-a')
b = threading.Thread(target=print_work_b, name='Thread-b')
a.start()
b.start()