SlideShare a Scribd company logo
1 of 5
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing
and multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared
memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
Advantages:
1) It doesn't block the user because threads are independent and you can perform
multiple operations at the same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in
a single thread.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking
to utilize the CPU. Multitasking can be achieved in two ways:
o Process-based Multitasking (Multiprocessing)
o Thread-based Multitasking (Multithreading)
1) Process-based Multitasking (Multiprocessing)
o Each process has an address in memory. In other words, each process allocates a
separate memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and loading
registers, memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.
In computing, a process is an instance of a computer program that
is being executed.
Any process has 3 basic components:
1.An executable program.
2.The associated data needed by the program (variables, work space,
buffers, etc.)
3.The execution context of the program (State of process)
A thread is an entity within a process that can be scheduled
for execution. Also, it is the smallest unit of processing that
can be performed in an OS (Operating System).
In simple words, a thread is a sequence of such instructions
within a program that can be executed independently of other code.
For simplicity, you can assume that a thread is simply a subset
of a process!
import threading
def print_cube(num):
"""
function to print cube of given num
"""
print("Cube: {}".format(num * num * num))
def print_square(num):
"""
function to print square of given num
"""
print("Square: {}".format(num * num))
if __name__ == "__main__":
# creating thread
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))
# starting thread 1
t1.start()
# starting thread 2
t2.start()
# wait until thread 1 is completely executed
t1.join()
# wait until thread 2 is completely executed
t2.join()
# both threads completely executed
print("Done!")
 To create a new thread, we create an object of Thread class. It takes following
arguments:
 target: the function to be executed by thread
 args: the arguments to be passed to the target function
In above example, we created 2 threads with different target functions:
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_cube, args=(10,))
 To start a thread, we use start method of Thread class.
 t1.start()
 t2.start()
 Once the threads start, the current program (you can think of it like a main
thread) also keeps on executing. In order to stop execution of current program
until a thread is complete, we use join method.
 t1.join()
 t2.join()
As a result, the current program will first wait for the completion of t1 and
then t2. Once, they are finished, the remaining statements of current program
are executed
import threading
import time
def square(num):
print("calculate square numbers:")
for n in num:
time.sleep(0.2)
print("square:",n*n)
def cube(num):
print("calculate cube numbers:")
for n in num:
time.sleep(0.2)
print("cube:", n * n*n)
arr=[2,3,4,5]
t=time.time()
'''t1=threading.Thread(target=square,ar
gs=(arr,))
t2=threading.Thread(target=cube,args=(a
rr,))
t1.start()
t2.start()
t1.join()
t2.join()'''
square(arr)
cube(arr)
print("done in:",time.time()-t)
print("completed my task")

More Related Content

Similar to Multi Threading.docx

OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
Multithreading
MultithreadingMultithreading
Multithreading
backdoor
 
OS Module-2.pptx
OS Module-2.pptxOS Module-2.pptx
OS Module-2.pptx
bleh23
 
Operating System 4 1193308760782240 2
Operating System 4 1193308760782240 2Operating System 4 1193308760782240 2
Operating System 4 1193308760782240 2
mona_hakmy
 
Operating System 4
Operating System 4Operating System 4
Operating System 4
tech2click
 
Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01
Aravindharamanan S
 

Similar to Multi Threading.docx (20)

Mca2050 computer architecture
Mca2050  computer architectureMca2050  computer architecture
Mca2050 computer architecture
 
Os Threads
Os ThreadsOs Threads
Os Threads
 
Internet Programming with Java
Internet Programming with JavaInternet Programming with Java
Internet Programming with Java
 
Java
JavaJava
Java
 
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
 
Threads
ThreadsThreads
Threads
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
 
Topic 4- processes.pptx
Topic 4- processes.pptxTopic 4- processes.pptx
Topic 4- processes.pptx
 
Multithreading
MultithreadingMultithreading
Multithreading
 
OS Module-2.pptx
OS Module-2.pptxOS Module-2.pptx
OS Module-2.pptx
 
Unit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdfUnit-3 MULTITHREADING-2.pdf
Unit-3 MULTITHREADING-2.pdf
 
Concurrency in java
Concurrency in javaConcurrency in java
Concurrency in java
 
Chapter 3 chapter reading task
Chapter 3 chapter reading taskChapter 3 chapter reading task
Chapter 3 chapter reading task
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
Operating System 4 1193308760782240 2
Operating System 4 1193308760782240 2Operating System 4 1193308760782240 2
Operating System 4 1193308760782240 2
 
Operating System 4
Operating System 4Operating System 4
Operating System 4
 
Generators & Decorators.pptx
Generators & Decorators.pptxGenerators & Decorators.pptx
Generators & Decorators.pptx
 
Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01
 
Threads
ThreadsThreads
Threads
 

More from manohar25689 (6)

Numpy in Python.docx
Numpy in Python.docxNumpy in Python.docx
Numpy in Python.docx
 
Modules in Python.docx
Modules in Python.docxModules in Python.docx
Modules in Python.docx
 
Logging in Python.docx
Logging in Python.docxLogging in Python.docx
Logging in Python.docx
 
controlstatementspy.docx
controlstatementspy.docxcontrolstatementspy.docx
controlstatementspy.docx
 
List Data Structure.docx
List Data Structure.docxList Data Structure.docx
List Data Structure.docx
 
File Handling in python.docx
File Handling in python.docxFile Handling in python.docx
File Handling in python.docx
 

Recently uploaded

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 

Recently uploaded (20)

social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 

Multi Threading.docx

  • 1. A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. However, we use multithreading than multiprocessing because threads use a shared memory area. They don't allocate separate memory area so saves memory, and context- switching between the threads takes less time than process. Advantages: 1) It doesn't block the user because threads are independent and you can perform multiple operations at the same time. 2) You can perform many operations together, so it saves time. 3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread. Multitasking Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved in two ways: o Process-based Multitasking (Multiprocessing) o Thread-based Multitasking (Multithreading) 1) Process-based Multitasking (Multiprocessing) o Each process has an address in memory. In other words, each process allocates a separate memory area. o A process is heavyweight. o Cost of communication between the process is high. o Switching from one process to another requires some time for saving and loading registers, memory maps, updating lists, etc. 2) Thread-based Multitasking (Multithreading) o Threads share the same address space. o A thread is lightweight. o Cost of communication between the thread is low. In computing, a process is an instance of a computer program that is being executed.
  • 2. Any process has 3 basic components: 1.An executable program. 2.The associated data needed by the program (variables, work space, buffers, etc.) 3.The execution context of the program (State of process) A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of processing that can be performed in an OS (Operating System). In simple words, a thread is a sequence of such instructions within a program that can be executed independently of other code. For simplicity, you can assume that a thread is simply a subset of a process! import threading def print_cube(num): """ function to print cube of given num
  • 3. """ print("Cube: {}".format(num * num * num)) def print_square(num): """ function to print square of given num """ print("Square: {}".format(num * num)) if __name__ == "__main__": # creating thread t1 = threading.Thread(target=print_square, args=(10,)) t2 = threading.Thread(target=print_cube, args=(10,)) # starting thread 1 t1.start() # starting thread 2 t2.start() # wait until thread 1 is completely executed t1.join() # wait until thread 2 is completely executed t2.join() # both threads completely executed print("Done!")  To create a new thread, we create an object of Thread class. It takes following arguments:  target: the function to be executed by thread  args: the arguments to be passed to the target function In above example, we created 2 threads with different target functions: t1 = threading.Thread(target=print_square, args=(10,)) t2 = threading.Thread(target=print_cube, args=(10,))  To start a thread, we use start method of Thread class.  t1.start()  t2.start()  Once the threads start, the current program (you can think of it like a main thread) also keeps on executing. In order to stop execution of current program until a thread is complete, we use join method.  t1.join()  t2.join() As a result, the current program will first wait for the completion of t1 and then t2. Once, they are finished, the remaining statements of current program are executed import threading import time
  • 4. def square(num): print("calculate square numbers:") for n in num: time.sleep(0.2) print("square:",n*n) def cube(num): print("calculate cube numbers:") for n in num: time.sleep(0.2) print("cube:", n * n*n) arr=[2,3,4,5] t=time.time() '''t1=threading.Thread(target=square,ar gs=(arr,)) t2=threading.Thread(target=cube,args=(a rr,)) t1.start() t2.start() t1.join() t2.join()''' square(arr) cube(arr)