SlideShare a Scribd company logo
PYTHON MULTITHREADING
CHAPTER – 4
THE BASICS OF SEARCH ENGINE FRIENDLY DESIGN & DEVELOPMENT
Copyright @ 2019 Learntek. All Rights Reserved. 3
Python Threading
In the previous article, you have seen the threading methods. In this article, you
will see daemon threads and locks.
Daemon Thread:
So far, we have created the non-daemon thread. What is the daemon
thread? When the main thread exits, it attempts to terminate all of its daemonic
child threads.
Consider an example of GUI as shown below
Copyright @ 2019 Learntek. All Rights Reserved. 4
Consider, by GUI input some calculation is being performed in the background and the
calculation is taking its time. If you click close button two courses of action can be
performed.
1.After clicking the close button the whole GUI window exists.
2.After clicking the close button the GUI window will wait for the completion of
background calculation.
Copyright @ 2019 Learntek. All Rights Reserved. 5
If the first course of action is performed then Daemon thread are being used in
background calculation. If the second course of action is performed then a Non-
daemon thread is being used in background calculation.
Let us understand with the help of code
import threading
import time
def n():
print ("Non deamon start")
print ("NOn daemoon exit")
Copyright @ 2019 Learntek. All Rights Reserved. 6
def d():
print (" daemon start")
time.sleep(5)
print (" daemon stop")
t = threading.Thread(name = "non-daemon",target=n)
d = threading.Thread(name = "daemon",target=d)
d.setDaemon(True)
d.start()
t.start()
Copyright @ 2019 Learntek. All Rights Reserved. 7
If method isDaemon() returns True then the thread is a daemon thread. The syntax
d.setDaemon(True) or d.daemon = True can be used to make daemon thread.
Let us see the output:
Copyright @ 2019 Learntek. All Rights Reserved. 8
Daemon thread will take 5 seconds to complete its task, but main did not wait for
the daemon thread. That’s why in the output there is no “daemon stop”
statement. Now remove the time. Sleep(5) from function d() and add it in n()
function.
See the code below.
Copyright @ 2019 Learntek. All Rights Reserved. 9
import threading
import time
def n():
print ("Non deamon start")
time.sleep(5)
print ("NOn daemoon exit")
def d():
print (" daemon start")
print (" daemon stop")
t = threading.Thread(name = "non-daemon",target=n)
d = threading.Thread(name = "daemon",target=d)
Copyright @ 2019 Learntek. All Rights Reserved. 10
d.setDaemon(True)
d.start()
t.start()
See the output:
Copyright @ 2019 Learntek. All Rights Reserved. 11
In the above example, all print statements are executed. The main thread had to wait
for the non-daemon process.
Note: If you use join statement for Daemon thread then the main thread has to wait
for the completion of Daemon thread’s task.
Learn Python + Advanced Python with our Experts
Copyright @ 2019 Learntek. All Rights Reserved. 12
Locks
Locks are the most fundamental synchronization mechanism provided by the
threading module. A lock is in one of two states, locked or unlocked. If a thread
attempts to hold a lock that’s already held by some other thread, execution of the
second thread is halted until the lock is released.
lock.acquire ():
Acquire a lock, blocks others until True (Default )
lock.locked():
Returns True if lock is locked, otherwise False.
lock.release():
Unlocks the lock
Copyright @ 2019 Learntek. All Rights Reserved. 13
Let us see one example.
import threading
import time
lock = threading.Lock()
list1 = []
def fun1(a):
lock.acquire()
list1.append(a)
lock.release()
for each in range(10):
Copyright @ 2019 Learntek. All Rights Reserved. 14
thread1 = threading.Thread(target=fun1, args=(each,))
thread1.start()
print ("List1 is : ", list1)
The lock = threading.Lock() is used to create a lock object.
The main problem with the lock is, the lock does not remember which thread
acquired the lock. Now two problem can be aroused.
Copyright @ 2019 Learntek. All Rights Reserved. 15
See the code below.
import threading
import time
lock = threading.Lock()
import datetime
t1 = datetime.datetime.now()
def second(n):
lock.acquire()
print (n)
def third():
Copyright @ 2019 Learntek. All Rights Reserved. 16
time.sleep(5)
lock.release()
print ("Thread3 ")
th1 = threading.Thread(target= second, args=("Thread1",))
th1.start()
th2 = threading.Thread(target= second, args=("Thread2",))
th2.start()
th3 = threading.Thread(target= third)
th3.start()
Copyright @ 2019 Learntek. All Rights Reserved. 17
th1.join()
th2.join()
th3.join()
t2 = datetime.datetime.now()
print ("Total time", t2-t1)
In the above code, a lock is acquired by thread1 and released by thread3. The
thread2 is trying to acquire the lock.
Let us see the output.
Copyright @ 2019 Learntek. All Rights Reserved. 18
From the sequence of execution, it is clear that the lock acquired by the thread1 got
released by the thread3.
Let see second problem.
Copyright @ 2019 Learntek. All Rights Reserved. 19
import threading
lock = threading.Lock()
def first(n):
lock.acquire()
a =12+n
lock.release()
print (a)
def second(n):
lock.acquire()
b = 12+n
Copyright @ 2019 Learntek. All Rights Reserved. 20
lock.release()
print (b)
def all():
lock.acquire()
first(2)
second(3)
lock.release()
th1 = threading.Thread(target= all)
th1.start()
Copyright @ 2019 Learntek. All Rights Reserved. 21
When you run the above code, deadlock would occur. In the function all thread
will acquire a lock, after acquiring the lock the first function will be called. The
thread will see the lock.acquire() statement. As this lock itself acquired by the
same python multithreading. But lock does not remember the thread which
acquired it.
In order to overcome above problem, we use Reentrant lock (RLock).
Just replace the threading.Lock with threading.Rlock
threading.RLock() — A factory function that returns a new reentrant lock
object. A reentrant lock must be released by the thread that acquired it. Once a
thread has acquired a reentrant lock, the same thread may acquire it again
without blocking; the thread must release it once for each time it has acquired it.
Copyright @ 2019 Learntek. All Rights Reserved. 22
Lock vs Rlock
The main difference is that a Lock can only be acquired once. It cannot be acquired
again until it is released. (After it’s been released, it can be re-acquired by any
thread).
An RLock, on the other hand, can be acquired multiple times, by the same thread. It
needs to be released the same number of times in order to be “unlocked”.
Another difference is that an acquired Lock can be released by any thread, while an
acquired RLock can only be released by the thread which acquired it.
Copyright @ 2019 Learntek. All Rights Reserved. 23
GIL
Thread-based parallelism is the standard way of writing parallel programs. However,
the Python interpreter is not fully thread-safe. In order to support multi-threaded
Python programs, a global lock called the Global Interpreter Lock (GIL) is used. This
means that only one thread can execute the Python code at the same time; Python
automatically switches to the next thread after a short period of time or when a
thread does something that may take a while. The GIL is not enough to avoid
problems in your own programs. Although, if multiple threads attempt to access the
same data object, it may end up in an inconsistent state.
Copyright @ 2019 Learntek. All Rights Reserved. 24
Let us see the example.
import datetime
def count(n):
t1 = datetime.datetime.now()
while n > 0:
n = n-1
t2 = datetime.datetime.now()
print (t2-t1)
count(100000000)
Copyright @ 2019 Learntek. All Rights Reserved. 25
In the above code, the count function is being run the main thread. Let see the time
taken by the thread.
Copyright @ 2019 Learntek. All Rights Reserved.
26
I ran the code three times, every time I got a similar result.
Let us create two thread, see the code below.
import datetime
from threading import Thread
def count(n):
while n > 0:
n = n-1
def count1(n):
while n > 0:
n = n-1
Copyright @ 2019 Learntek. All Rights Reserved. 27
t1 = datetime.datetime.now()
thread1 = Thread(target = count, args=(100000000,))
thread2 = Thread(target = count1, args= (100000000,))
thread1.start()
thread2.start()
thread1.join()
thread2.join()
t2 = datetime.datetime.now()
print (t2-t1)
Copyright @ 2019 Learntek. All Rights Reserved. 28
In the above, two threads have been created to be run in parallel.
Let us see the result.
Copyright @ 2019 Learntek. All Rights Reserved. 29
You can the above code took almost 10 seconds which is the double of the
previous program, it means, only the main thread act as multithreading. But above
experiment, we can conclude that Multithreading is defined as the ability of a
processor to execute multiple threads concurrently.
In a simple, single-core CPU, it is achieved using frequent switching between
threads. This is termed as context switching.
In context switching, the state of a thread is saved and state of another thread is
loaded whenever any interrupt (due to I/O or manually set) takes place. Context
switching takes place so frequently that all the threads appear to be running
parallelly(this is termed as multitasking)
Copyright @ 2019 Learntek. All Rights Reserved. 30
Copyright @ 2019 Learntek. All Rights Reserved. 31
For more Online Training Courses, Please
contact
Email : info@learntek.org
USA : +1734 418 2465
India : +91 40 4018 1306
+91 7799713624

More Related Content

What's hot

Programming Assignment Help
Programming Assignment HelpProgramming Assignment Help
Programming Assignment Help
Programming Homework Help
 
Java 8 - Stamped Lock
Java 8 - Stamped LockJava 8 - Stamped Lock
Java 8 - Stamped Lock
Haim Yadid
 
computer notes - Inter process communication
computer notes - Inter process communicationcomputer notes - Inter process communication
computer notes - Inter process communication
ecomputernotes
 
Metrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMetrics ekon 14_2_kleiner
Metrics ekon 14_2_kleiner
Max Kleiner
 
Operating System Assignment Help
Operating System Assignment HelpOperating System Assignment Help
Operating System Assignment Help
Programming Homework Help
 
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
Tsundere Chen
 
5 stream ciphers
5 stream ciphers5 stream ciphers
5 stream ciphers
Harish Sahu
 
Threads in python
Threads in pythonThreads in python
Why rust?
Why rust?Why rust?
Why rust?
Mats Kindahl
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
Neeraj Kaushik
 
Rass presentation
Rass presentationRass presentation
Rass presentation
Shalini Guha
 
TensorFlow Lite (r1.5) & Android 8.1 Neural Network API
TensorFlow Lite (r1.5) & Android 8.1 Neural Network APITensorFlow Lite (r1.5) & Android 8.1 Neural Network API
TensorFlow Lite (r1.5) & Android 8.1 Neural Network API
Mr. Vengineer
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
Ganesh Samarthyam
 
Async await in C++
Async await in C++Async await in C++
Async await in C++
cppfrug
 
PyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtimePyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtime
National Cheng Kung University
 
The Ring programming language version 1.5.3 book - Part 189 of 194
The Ring programming language version 1.5.3 book - Part 189 of 194The Ring programming language version 1.5.3 book - Part 189 of 194
The Ring programming language version 1.5.3 book - Part 189 of 194
Mahmoud Samir Fayed
 
EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4
Max Kleiner
 
Use of an Oscilloscope - maXbox Starter33
Use of an Oscilloscope - maXbox Starter33Use of an Oscilloscope - maXbox Starter33
Use of an Oscilloscope - maXbox Starter33
Max Kleiner
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
mckennadglyn
 
Synchronization
SynchronizationSynchronization
Synchronization
David Evans
 

What's hot (20)

Programming Assignment Help
Programming Assignment HelpProgramming Assignment Help
Programming Assignment Help
 
Java 8 - Stamped Lock
Java 8 - Stamped LockJava 8 - Stamped Lock
Java 8 - Stamped Lock
 
computer notes - Inter process communication
computer notes - Inter process communicationcomputer notes - Inter process communication
computer notes - Inter process communication
 
Metrics ekon 14_2_kleiner
Metrics ekon 14_2_kleinerMetrics ekon 14_2_kleiner
Metrics ekon 14_2_kleiner
 
Operating System Assignment Help
Operating System Assignment HelpOperating System Assignment Help
Operating System Assignment Help
 
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
 
5 stream ciphers
5 stream ciphers5 stream ciphers
5 stream ciphers
 
Threads in python
Threads in pythonThreads in python
Threads in python
 
Why rust?
Why rust?Why rust?
Why rust?
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Rass presentation
Rass presentationRass presentation
Rass presentation
 
TensorFlow Lite (r1.5) & Android 8.1 Neural Network API
TensorFlow Lite (r1.5) & Android 8.1 Neural Network APITensorFlow Lite (r1.5) & Android 8.1 Neural Network API
TensorFlow Lite (r1.5) & Android 8.1 Neural Network API
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Async await in C++
Async await in C++Async await in C++
Async await in C++
 
PyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtimePyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtime
 
The Ring programming language version 1.5.3 book - Part 189 of 194
The Ring programming language version 1.5.3 book - Part 189 of 194The Ring programming language version 1.5.3 book - Part 189 of 194
The Ring programming language version 1.5.3 book - Part 189 of 194
 
EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4
 
Use of an Oscilloscope - maXbox Starter33
Use of an Oscilloscope - maXbox Starter33Use of an Oscilloscope - maXbox Starter33
Use of an Oscilloscope - maXbox Starter33
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Synchronization
SynchronizationSynchronization
Synchronization
 

Similar to Python multithreading

Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
Mahmoud Ouf
 
Computer Networks Omnet
Computer Networks OmnetComputer Networks Omnet
Computer Networks Omnet
Shivam Maheshwari
 
Essentials of Multithreaded System Programming in C++
Essentials of Multithreaded System Programming in C++Essentials of Multithreaded System Programming in C++
Essentials of Multithreaded System Programming in C++
Shuo Chen
 
Generators & Decorators.pptx
Generators & Decorators.pptxGenerators & Decorators.pptx
Generators & Decorators.pptx
IrfanShaik98
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
Mohammed Sikander
 
S044125129
S044125129S044125129
S044125129
IJERA Editor
 
Multithreaded_Programming_in_Python.pdf
Multithreaded_Programming_in_Python.pdfMultithreaded_Programming_in_Python.pdf
Multithreaded_Programming_in_Python.pdf
giridharsripathi
 
TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26
Max Kleiner
 
POSIX Threads
POSIX ThreadsPOSIX Threads
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
Ganesh Samarthyam
 
L Fu - Dao: a novel programming language for bioinformatics
L Fu - Dao: a novel programming language for bioinformaticsL Fu - Dao: a novel programming language for bioinformatics
L Fu - Dao: a novel programming language for bioinformatics
Jan Aerts
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAChapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Maulik Borsaniya
 
360|Flex Greenthreading In Flex
360|Flex Greenthreading In Flex360|Flex Greenthreading In Flex
360|Flex Greenthreading In Flex
Huyen Tue Dao
 
Linux scheduler
Linux schedulerLinux scheduler
Linux scheduler
Liran Ben Haim
 
Threads
ThreadsThreads
Threads
Sameer Shaik
 
concurrency
concurrencyconcurrency
concurrency
Jonathan Wagoner
 
Multithreading by rj
Multithreading by rjMultithreading by rj
Multi Threading
Multi ThreadingMulti Threading
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
Java adv
Java advJava adv

Similar to Python multithreading (20)

Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
 
Computer Networks Omnet
Computer Networks OmnetComputer Networks Omnet
Computer Networks Omnet
 
Essentials of Multithreaded System Programming in C++
Essentials of Multithreaded System Programming in C++Essentials of Multithreaded System Programming in C++
Essentials of Multithreaded System Programming in C++
 
Generators & Decorators.pptx
Generators & Decorators.pptxGenerators & Decorators.pptx
Generators & Decorators.pptx
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
 
S044125129
S044125129S044125129
S044125129
 
Multithreaded_Programming_in_Python.pdf
Multithreaded_Programming_in_Python.pdfMultithreaded_Programming_in_Python.pdf
Multithreaded_Programming_in_Python.pdf
 
TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26
 
POSIX Threads
POSIX ThreadsPOSIX Threads
POSIX Threads
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
L Fu - Dao: a novel programming language for bioinformatics
L Fu - Dao: a novel programming language for bioinformaticsL Fu - Dao: a novel programming language for bioinformatics
L Fu - Dao: a novel programming language for bioinformatics
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAChapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
 
360|Flex Greenthreading In Flex
360|Flex Greenthreading In Flex360|Flex Greenthreading In Flex
360|Flex Greenthreading In Flex
 
Linux scheduler
Linux schedulerLinux scheduler
Linux scheduler
 
Threads
ThreadsThreads
Threads
 
concurrency
concurrencyconcurrency
concurrency
 
Multithreading by rj
Multithreading by rjMultithreading by rj
Multithreading by rj
 
Multi Threading
Multi ThreadingMulti Threading
Multi Threading
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Java adv
Java advJava adv
Java adv
 

More from Janu Jahnavi

Analytics using r programming
Analytics using r programmingAnalytics using r programming
Analytics using r programming
Janu Jahnavi
 
Software testing
Software testingSoftware testing
Software testing
Janu Jahnavi
 
Software testing
Software testingSoftware testing
Software testing
Janu Jahnavi
 
Spring
SpringSpring
Spring
Janu Jahnavi
 
Stack skills
Stack skillsStack skills
Stack skills
Janu Jahnavi
 
Ui devopler
Ui devoplerUi devopler
Ui devopler
Janu Jahnavi
 
Apache flink
Apache flinkApache flink
Apache flink
Janu Jahnavi
 
Apache flink
Apache flinkApache flink
Apache flink
Janu Jahnavi
 
Angular js
Angular jsAngular js
Angular js
Janu Jahnavi
 
Mysql python
Mysql pythonMysql python
Mysql python
Janu Jahnavi
 
Mysql python
Mysql pythonMysql python
Mysql python
Janu Jahnavi
 
Ruby with cucmber
Ruby with cucmberRuby with cucmber
Ruby with cucmber
Janu Jahnavi
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
Janu Jahnavi
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
Janu Jahnavi
 
Google cloud platform
Google cloud platformGoogle cloud platform
Google cloud platform
Janu Jahnavi
 
Google cloud Platform
Google cloud PlatformGoogle cloud Platform
Google cloud Platform
Janu Jahnavi
 
Apache spark with java 8
Apache spark with java 8Apache spark with java 8
Apache spark with java 8
Janu Jahnavi
 
Apache spark with java 8
Apache spark with java 8Apache spark with java 8
Apache spark with java 8
Janu Jahnavi
 
Categorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk pythonCategorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk python
Janu Jahnavi
 
Categorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk pythonCategorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk python
Janu Jahnavi
 

More from Janu Jahnavi (20)

Analytics using r programming
Analytics using r programmingAnalytics using r programming
Analytics using r programming
 
Software testing
Software testingSoftware testing
Software testing
 
Software testing
Software testingSoftware testing
Software testing
 
Spring
SpringSpring
Spring
 
Stack skills
Stack skillsStack skills
Stack skills
 
Ui devopler
Ui devoplerUi devopler
Ui devopler
 
Apache flink
Apache flinkApache flink
Apache flink
 
Apache flink
Apache flinkApache flink
Apache flink
 
Angular js
Angular jsAngular js
Angular js
 
Mysql python
Mysql pythonMysql python
Mysql python
 
Mysql python
Mysql pythonMysql python
Mysql python
 
Ruby with cucmber
Ruby with cucmberRuby with cucmber
Ruby with cucmber
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
 
Apache kafka
Apache kafkaApache kafka
Apache kafka
 
Google cloud platform
Google cloud platformGoogle cloud platform
Google cloud platform
 
Google cloud Platform
Google cloud PlatformGoogle cloud Platform
Google cloud Platform
 
Apache spark with java 8
Apache spark with java 8Apache spark with java 8
Apache spark with java 8
 
Apache spark with java 8
Apache spark with java 8Apache spark with java 8
Apache spark with java 8
 
Categorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk pythonCategorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk python
 
Categorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk pythonCategorizing and pos tagging with nltk python
Categorizing and pos tagging with nltk python
 

Recently uploaded

Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
Jyoti Chand
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
iammrhaywood
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Denish Jangid
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
Himanshu Rai
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
EduSkills OECD
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
Nguyen Thanh Tu Collection
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
S. Raj Kumar
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
Nguyen Thanh Tu Collection
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 

Recently uploaded (20)

Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptxNEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
NEWSPAPERS - QUESTION 1 - REVISION POWERPOINT.pptx
 
Chapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptxChapter wise All Notes of First year Basic Civil Engineering.pptx
Chapter wise All Notes of First year Basic Civil Engineering.pptx
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 

Python multithreading

  • 2. CHAPTER – 4 THE BASICS OF SEARCH ENGINE FRIENDLY DESIGN & DEVELOPMENT
  • 3. Copyright @ 2019 Learntek. All Rights Reserved. 3 Python Threading In the previous article, you have seen the threading methods. In this article, you will see daemon threads and locks. Daemon Thread: So far, we have created the non-daemon thread. What is the daemon thread? When the main thread exits, it attempts to terminate all of its daemonic child threads. Consider an example of GUI as shown below
  • 4. Copyright @ 2019 Learntek. All Rights Reserved. 4 Consider, by GUI input some calculation is being performed in the background and the calculation is taking its time. If you click close button two courses of action can be performed. 1.After clicking the close button the whole GUI window exists. 2.After clicking the close button the GUI window will wait for the completion of background calculation.
  • 5. Copyright @ 2019 Learntek. All Rights Reserved. 5 If the first course of action is performed then Daemon thread are being used in background calculation. If the second course of action is performed then a Non- daemon thread is being used in background calculation. Let us understand with the help of code import threading import time def n(): print ("Non deamon start") print ("NOn daemoon exit")
  • 6. Copyright @ 2019 Learntek. All Rights Reserved. 6 def d(): print (" daemon start") time.sleep(5) print (" daemon stop") t = threading.Thread(name = "non-daemon",target=n) d = threading.Thread(name = "daemon",target=d) d.setDaemon(True) d.start() t.start()
  • 7. Copyright @ 2019 Learntek. All Rights Reserved. 7 If method isDaemon() returns True then the thread is a daemon thread. The syntax d.setDaemon(True) or d.daemon = True can be used to make daemon thread. Let us see the output:
  • 8. Copyright @ 2019 Learntek. All Rights Reserved. 8 Daemon thread will take 5 seconds to complete its task, but main did not wait for the daemon thread. That’s why in the output there is no “daemon stop” statement. Now remove the time. Sleep(5) from function d() and add it in n() function. See the code below.
  • 9. Copyright @ 2019 Learntek. All Rights Reserved. 9 import threading import time def n(): print ("Non deamon start") time.sleep(5) print ("NOn daemoon exit") def d(): print (" daemon start") print (" daemon stop") t = threading.Thread(name = "non-daemon",target=n) d = threading.Thread(name = "daemon",target=d)
  • 10. Copyright @ 2019 Learntek. All Rights Reserved. 10 d.setDaemon(True) d.start() t.start() See the output:
  • 11. Copyright @ 2019 Learntek. All Rights Reserved. 11 In the above example, all print statements are executed. The main thread had to wait for the non-daemon process. Note: If you use join statement for Daemon thread then the main thread has to wait for the completion of Daemon thread’s task. Learn Python + Advanced Python with our Experts
  • 12. Copyright @ 2019 Learntek. All Rights Reserved. 12 Locks Locks are the most fundamental synchronization mechanism provided by the threading module. A lock is in one of two states, locked or unlocked. If a thread attempts to hold a lock that’s already held by some other thread, execution of the second thread is halted until the lock is released. lock.acquire (): Acquire a lock, blocks others until True (Default ) lock.locked(): Returns True if lock is locked, otherwise False. lock.release(): Unlocks the lock
  • 13. Copyright @ 2019 Learntek. All Rights Reserved. 13 Let us see one example. import threading import time lock = threading.Lock() list1 = [] def fun1(a): lock.acquire() list1.append(a) lock.release() for each in range(10):
  • 14. Copyright @ 2019 Learntek. All Rights Reserved. 14 thread1 = threading.Thread(target=fun1, args=(each,)) thread1.start() print ("List1 is : ", list1) The lock = threading.Lock() is used to create a lock object. The main problem with the lock is, the lock does not remember which thread acquired the lock. Now two problem can be aroused.
  • 15. Copyright @ 2019 Learntek. All Rights Reserved. 15 See the code below. import threading import time lock = threading.Lock() import datetime t1 = datetime.datetime.now() def second(n): lock.acquire() print (n) def third():
  • 16. Copyright @ 2019 Learntek. All Rights Reserved. 16 time.sleep(5) lock.release() print ("Thread3 ") th1 = threading.Thread(target= second, args=("Thread1",)) th1.start() th2 = threading.Thread(target= second, args=("Thread2",)) th2.start() th3 = threading.Thread(target= third) th3.start()
  • 17. Copyright @ 2019 Learntek. All Rights Reserved. 17 th1.join() th2.join() th3.join() t2 = datetime.datetime.now() print ("Total time", t2-t1) In the above code, a lock is acquired by thread1 and released by thread3. The thread2 is trying to acquire the lock. Let us see the output.
  • 18. Copyright @ 2019 Learntek. All Rights Reserved. 18 From the sequence of execution, it is clear that the lock acquired by the thread1 got released by the thread3. Let see second problem.
  • 19. Copyright @ 2019 Learntek. All Rights Reserved. 19 import threading lock = threading.Lock() def first(n): lock.acquire() a =12+n lock.release() print (a) def second(n): lock.acquire() b = 12+n
  • 20. Copyright @ 2019 Learntek. All Rights Reserved. 20 lock.release() print (b) def all(): lock.acquire() first(2) second(3) lock.release() th1 = threading.Thread(target= all) th1.start()
  • 21. Copyright @ 2019 Learntek. All Rights Reserved. 21 When you run the above code, deadlock would occur. In the function all thread will acquire a lock, after acquiring the lock the first function will be called. The thread will see the lock.acquire() statement. As this lock itself acquired by the same python multithreading. But lock does not remember the thread which acquired it. In order to overcome above problem, we use Reentrant lock (RLock). Just replace the threading.Lock with threading.Rlock threading.RLock() — A factory function that returns a new reentrant lock object. A reentrant lock must be released by the thread that acquired it. Once a thread has acquired a reentrant lock, the same thread may acquire it again without blocking; the thread must release it once for each time it has acquired it.
  • 22. Copyright @ 2019 Learntek. All Rights Reserved. 22 Lock vs Rlock The main difference is that a Lock can only be acquired once. It cannot be acquired again until it is released. (After it’s been released, it can be re-acquired by any thread). An RLock, on the other hand, can be acquired multiple times, by the same thread. It needs to be released the same number of times in order to be “unlocked”. Another difference is that an acquired Lock can be released by any thread, while an acquired RLock can only be released by the thread which acquired it.
  • 23. Copyright @ 2019 Learntek. All Rights Reserved. 23 GIL Thread-based parallelism is the standard way of writing parallel programs. However, the Python interpreter is not fully thread-safe. In order to support multi-threaded Python programs, a global lock called the Global Interpreter Lock (GIL) is used. This means that only one thread can execute the Python code at the same time; Python automatically switches to the next thread after a short period of time or when a thread does something that may take a while. The GIL is not enough to avoid problems in your own programs. Although, if multiple threads attempt to access the same data object, it may end up in an inconsistent state.
  • 24. Copyright @ 2019 Learntek. All Rights Reserved. 24 Let us see the example. import datetime def count(n): t1 = datetime.datetime.now() while n > 0: n = n-1 t2 = datetime.datetime.now() print (t2-t1) count(100000000)
  • 25. Copyright @ 2019 Learntek. All Rights Reserved. 25 In the above code, the count function is being run the main thread. Let see the time taken by the thread.
  • 26. Copyright @ 2019 Learntek. All Rights Reserved. 26 I ran the code three times, every time I got a similar result. Let us create two thread, see the code below. import datetime from threading import Thread def count(n): while n > 0: n = n-1 def count1(n): while n > 0: n = n-1
  • 27. Copyright @ 2019 Learntek. All Rights Reserved. 27 t1 = datetime.datetime.now() thread1 = Thread(target = count, args=(100000000,)) thread2 = Thread(target = count1, args= (100000000,)) thread1.start() thread2.start() thread1.join() thread2.join() t2 = datetime.datetime.now() print (t2-t1)
  • 28. Copyright @ 2019 Learntek. All Rights Reserved. 28 In the above, two threads have been created to be run in parallel. Let us see the result.
  • 29. Copyright @ 2019 Learntek. All Rights Reserved. 29 You can the above code took almost 10 seconds which is the double of the previous program, it means, only the main thread act as multithreading. But above experiment, we can conclude that Multithreading is defined as the ability of a processor to execute multiple threads concurrently. In a simple, single-core CPU, it is achieved using frequent switching between threads. This is termed as context switching. In context switching, the state of a thread is saved and state of another thread is loaded whenever any interrupt (due to I/O or manually set) takes place. Context switching takes place so frequently that all the threads appear to be running parallelly(this is termed as multitasking)
  • 30. Copyright @ 2019 Learntek. All Rights Reserved. 30
  • 31. Copyright @ 2019 Learntek. All Rights Reserved. 31 For more Online Training Courses, Please contact Email : info@learntek.org USA : +1734 418 2465 India : +91 40 4018 1306 +91 7799713624