SlideShare a Scribd company logo
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

PPTX
Engineeering Operating systemsOS UNIT 3 Threads.pptx
PDF
Multithreaded_Programming_in_Python.pdf
PDF
concurrency
PPTX
Multithreading.pptx
PDF
Multithreading Introduction and Lifecyle of thread
PPTX
introduction to java Multithreading presentation.pptx
PPTX
Multithreading in java
Engineeering Operating systemsOS UNIT 3 Threads.pptx
Multithreaded_Programming_in_Python.pdf
concurrency
Multithreading.pptx
Multithreading Introduction and Lifecyle of thread
introduction to java Multithreading presentation.pptx
Multithreading in java

Similar to Multi Threading.docx (20)

PPT
4.Process.ppt
PPTX
Introdution and objectives of Thread.pptx
PPTX
MULTI THREADING.pptx
DOCX
Mca2050 computer architecture
PPT
Os Threads
PPTX
Internet Programming with Java
PPTX
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
PPTX
Threads
PPTX
advanced java programming paradigms presentation
PPTX
OOPS object oriented programming UNIT-4.pptx
PPT
Java Performance, Threading and Concurrent Data Structures
PDF
Threads operating system slides easy understand
PPTX
Topic 4- processes.pptx
PPT
Multithreading
PPTX
OS Module-2.pptx
PDF
Unit-3 MULTITHREADING-2.pdf
PDF
Concurrency in java
PPTX
Chapter 3 chapter reading task
PDF
Class notes(week 9) on multithreading
4.Process.ppt
Introdution and objectives of Thread.pptx
MULTI THREADING.pptx
Mca2050 computer architecture
Os Threads
Internet Programming with Java
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Threads
advanced java programming paradigms presentation
OOPS object oriented programming UNIT-4.pptx
Java Performance, Threading and Concurrent Data Structures
Threads operating system slides easy understand
Topic 4- processes.pptx
Multithreading
OS Module-2.pptx
Unit-3 MULTITHREADING-2.pdf
Concurrency in java
Chapter 3 chapter reading task
Class notes(week 9) on multithreading
Ad

More from manohar25689 (6)

DOCX
Numpy in Python.docx
DOCX
Modules in Python.docx
DOCX
Logging in Python.docx
DOCX
controlstatementspy.docx
DOCX
List Data Structure.docx
DOCX
File Handling in python.docx
Numpy in Python.docx
Modules in Python.docx
Logging in Python.docx
controlstatementspy.docx
List Data Structure.docx
File Handling in python.docx
Ad

Recently uploaded (20)

PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PPTX
master seminar digital applications in india
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Institutional Correction lecture only . . .
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Complications of Minimal Access Surgery at WLH
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Pharma ospi slides which help in ospi learning
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Cell Types and Its function , kingdom of life
O5-L3 Freight Transport Ops (International) V1.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Pharmacology of Heart Failure /Pharmacotherapy of CHF
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Week 4 Term 3 Study Techniques revisited.pptx
master seminar digital applications in india
2.FourierTransform-ShortQuestionswithAnswers.pdf
Microbial disease of the cardiovascular and lymphatic systems
Institutional Correction lecture only . . .
Abdominal Access Techniques with Prof. Dr. R K Mishra
Complications of Minimal Access Surgery at WLH
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPH.pptx obstetrics and gynecology in nursing
Pharma ospi slides which help in ospi learning
human mycosis Human fungal infections are called human mycosis..pptx
Final Presentation General Medicine 03-08-2024.pptx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Cell Types and Its function , kingdom of life

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)