SlideShare uma empresa Scribd logo
1 de 19
Baixar para ler offline
Part II
Process Management
    Chapter 4: Threads


                         1
What Is a Thread?
§ A thread, also known as lightweight process
  (LWP), is a basic unit of CPU execution.
§ A thread has a thread ID, a program counter, a
  register set, and a stack. Thus, it is similar to a
  process has.
§ However, a thread shares with other threads in
  the same process its code section, data section,
  and other OS resources (e.g., files and signals).
§ A process, or heavyweight process, has a single
  thread of control.

                                                    2
Single Threaded and
           Multithreaded Process
Single-threaded process   Multithreaded Process




                                                  3
Benefits of Using Threads
§ Responsiveness: Other parts (i.e., threads) of a
  program may still be running even if one part
  (e.g., a thread) is blocked.
§ Resource Sharing: Threads of a process, by
  default, share many system resources (e.g., files
  and memory).
§ Economy: Creating and terminating processes,
  allocating memory and resources, and context
  switching processes are very time consuming.
§ Utilization of Multiprocessor Architecture:
  Multiple CPUs can run multiple threads of the
  same process. No program change is necessary.
                                                      4
User and Kernel Threads: 1/3
q User Threads:
   vUser threads are supported at the user level.
    The kernel is not aware of user threads.
   vA library provides all support for thread
    creation, termination, joining, and scheduling.
   vThere is no kernel intervention, and, hence,
    user threads are usually more efficient.
   vUnfortunately, since the kernel only recognizes
    the containing process (of the threads), if one
    thread is blocked, every other threads of the same
    process are also blocked because the containing
    process is blocked.
                                                    5
User and Kernel Threads: 2/3
qKernel threads:
 vKernel threads are directly supported by the
   kernel. The kernel does thread creation,
   termination, joining, and scheduling in kernel
   space.
 vKernel threads are usually slower than the user
   threads.
 vHowever, blocking one thread will not cause other
   threads of the same process to block. The kernel
   simply runs other threads.
 vIn a multiprocessor environment, the kernel can
   schedule threads on different processors.      6
User and Kernel Threads: 3/3




                               7
Multithreading Models
qDifferent systems support threads in different
 ways. Here are three commonly seen thread
 models:
 vMany-to-One Model:One kernel thread (or
   process) has multiple user threads. Thus, this
   is a user thread model.
 vOne-to-One Model: one user thread maps to
   one kernel thread (e.g., Linux and Windows).
 vMany-to-Many Model: Multiple user threads
   maps to a number of kernel threads.
                                                8
Many-to-One Model




                    9
One-to-One Model: 1/2
An Extreme Case: Traditional Unix




                                    10
One-to-One Model: 2/2




                        11
Many-to-Many Model




                     12
Thread Issues

§   How Does a Thread Fork?
§   Thread Cancellation
§   Signal Handling
§   Thread-Specific Data
§   What Is Thread-Safe?



                              13
How Does a Thread Fork?
qIf a thread forks, does the new process:
  vduplicate all threads?
  vcontain only the forking thread (i.e., single-
    threaded)?
qSome systems have two fork system calls, one
 for each case.



                                                    14
Thread Cancellation: 1/2
qThread cancellation means terminating a thread
 before it has completed. The thread that is to be
 cancelled is the target thread.
qThere are two types:
  vAsynchronous Cancellation: the target thread
   terminates immediately.
  vDeferred Cancellation: The target thread can
   periodically check if it should terminate,
   allowing the target thread an opportunity to
   terminate itself in an orderly fashion. The
   point a thread can terminate itself is a
   cancellation point.
                                                15
Thread Cancellation: 2/2
qProblem: With asynchronous cancellation, if the
 target thread owns some system-wide resources, the
 system may not be able to reclaim all recourses
 owned by the target thread.
qWith deferred cancellation, the target thread
 determines the time to terminate itself. Reclaiming
 resources is not a problem.
qMost systems implement asynchronous cancellation
 for processes (e.g., use the kill system call) and
 threads.
qPthread supports deferred cancellation.
                                                16
Signal Handling
§ Signals is a way the OS uses to notify a
  process that some event has happened.
§ Once a signal occurs, who is going to
  handle it? The process, or one of the
  threads?
§ This is a very complex issue and will be
  discussed later in this course.


                                             17
Thread-Specific Data/Thread-Safe
qData that a thread needs for its own operation are
 thread-specific.
qPoor support for thread-specific data could cause
 problem. For example, while threads have their
 own stacks, they share the heap.
qWhat if two malloc() or new are executed at the
 same time requesting for memory from the heap?
 Or, two printf or cout are run simultaneously?
qIf a library can be used by multiple threads
 properly, it is a thread-safe one.
                                                 18
Thread Pool
qWhile we know that managing threads are more
 efficient than managing processes, creating and
 terminating threads are still not free.
qAfter a process is created, one can immediately
 create a number of threads and have them waiting.
qWhen a new task occurs, one can wake up one of
 the waiting threads and assign it the work. After
 this thread completes the task, it goes back to wait.
qIn this way, we save the number of thread creation
 and termination.
qThese threads are said in a thread pool.
                                                   19

Mais conteúdo relacionado

Mais procurados

deadlock handling
deadlock handlingdeadlock handling
deadlock handlingSuraj Kumar
 
Threads in Operating System | Multithreading | Interprocess Communication
Threads in Operating System | Multithreading | Interprocess CommunicationThreads in Operating System | Multithreading | Interprocess Communication
Threads in Operating System | Multithreading | Interprocess CommunicationShivam Mitra
 
Distributed operating system
Distributed operating systemDistributed operating system
Distributed operating systemudaya khanal
 
OS Process and Thread Concepts
OS Process and Thread ConceptsOS Process and Thread Concepts
OS Process and Thread Conceptssgpraju
 
Computer memory management
Computer memory managementComputer memory management
Computer memory managementKumar
 
Processes and Processors in Distributed Systems
Processes and Processors in Distributed SystemsProcesses and Processors in Distributed Systems
Processes and Processors in Distributed SystemsDr Sandeep Kumar Poonia
 
Operating Systems Process Scheduling Algorithms
Operating Systems   Process Scheduling AlgorithmsOperating Systems   Process Scheduling Algorithms
Operating Systems Process Scheduling Algorithmssathish sak
 
Synchronization hardware
Synchronization hardwareSynchronization hardware
Synchronization hardwareSaeram Butt
 
Multithreading models.ppt
Multithreading models.pptMultithreading models.ppt
Multithreading models.pptLuis Goldster
 
Reader/writer problem
Reader/writer problemReader/writer problem
Reader/writer problemRinkuMonani
 
Unit II - 2 - Operating System - Threads
Unit II - 2 - Operating System - ThreadsUnit II - 2 - Operating System - Threads
Unit II - 2 - Operating System - Threadscscarcas
 
CPU Scheduling in OS Presentation
CPU Scheduling in OS  PresentationCPU Scheduling in OS  Presentation
CPU Scheduling in OS Presentationusmankiyani1
 

Mais procurados (20)

deadlock handling
deadlock handlingdeadlock handling
deadlock handling
 
Threads in Operating System | Multithreading | Interprocess Communication
Threads in Operating System | Multithreading | Interprocess CommunicationThreads in Operating System | Multithreading | Interprocess Communication
Threads in Operating System | Multithreading | Interprocess Communication
 
Distributed operating system
Distributed operating systemDistributed operating system
Distributed operating system
 
Parallel processing
Parallel processingParallel processing
Parallel processing
 
OS Process and Thread Concepts
OS Process and Thread ConceptsOS Process and Thread Concepts
OS Process and Thread Concepts
 
Computer memory management
Computer memory managementComputer memory management
Computer memory management
 
Processes and Processors in Distributed Systems
Processes and Processors in Distributed SystemsProcesses and Processors in Distributed Systems
Processes and Processors in Distributed Systems
 
Operating Systems Process Scheduling Algorithms
Operating Systems   Process Scheduling AlgorithmsOperating Systems   Process Scheduling Algorithms
Operating Systems Process Scheduling Algorithms
 
SCHEDULING ALGORITHMS
SCHEDULING ALGORITHMSSCHEDULING ALGORITHMS
SCHEDULING ALGORITHMS
 
Lecture 3 threads
Lecture 3   threadsLecture 3   threads
Lecture 3 threads
 
Mainframe systems
Mainframe systemsMainframe systems
Mainframe systems
 
Process state in OS
Process state in OSProcess state in OS
Process state in OS
 
Process scheduling
Process schedulingProcess scheduling
Process scheduling
 
Synchronization hardware
Synchronization hardwareSynchronization hardware
Synchronization hardware
 
Multithreading models.ppt
Multithreading models.pptMultithreading models.ppt
Multithreading models.ppt
 
Kernels and its types
Kernels and its typesKernels and its types
Kernels and its types
 
Reader/writer problem
Reader/writer problemReader/writer problem
Reader/writer problem
 
Unit II - 2 - Operating System - Threads
Unit II - 2 - Operating System - ThreadsUnit II - 2 - Operating System - Threads
Unit II - 2 - Operating System - Threads
 
Desktop and multiprocessor systems
Desktop and multiprocessor systemsDesktop and multiprocessor systems
Desktop and multiprocessor systems
 
CPU Scheduling in OS Presentation
CPU Scheduling in OS  PresentationCPU Scheduling in OS  Presentation
CPU Scheduling in OS Presentation
 

Destaque

Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#Rizwan Ali
 
Processor / CPU Scheduling
Processor / CPU SchedulingProcessor / CPU Scheduling
Processor / CPU SchedulingIzaz Roghani
 
Programação Concorrente - Aula 02
Programação Concorrente - Aula 02Programação Concorrente - Aula 02
Programação Concorrente - Aula 02thomasdacosta
 
Address Binding Scheme
Address Binding SchemeAddress Binding Scheme
Address Binding SchemeRajesh Piryani
 
Logical Clocks (Distributed computing)
Logical Clocks (Distributed computing)Logical Clocks (Distributed computing)
Logical Clocks (Distributed computing)Sri Prasanna
 
Synchronization in distributed systems
Synchronization in distributed systems Synchronization in distributed systems
Synchronization in distributed systems SHATHAN
 

Destaque (10)

Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#
 
Reproduction-PUC_II
Reproduction-PUC_IIReproduction-PUC_II
Reproduction-PUC_II
 
Processor / CPU Scheduling
Processor / CPU SchedulingProcessor / CPU Scheduling
Processor / CPU Scheduling
 
Programação Concorrente - Aula 02
Programação Concorrente - Aula 02Programação Concorrente - Aula 02
Programação Concorrente - Aula 02
 
Address Binding Scheme
Address Binding SchemeAddress Binding Scheme
Address Binding Scheme
 
Threads
ThreadsThreads
Threads
 
Logical Clocks (Distributed computing)
Logical Clocks (Distributed computing)Logical Clocks (Distributed computing)
Logical Clocks (Distributed computing)
 
Processes and threads
Processes and threadsProcesses and threads
Processes and threads
 
Synchronization in distributed systems
Synchronization in distributed systems Synchronization in distributed systems
Synchronization in distributed systems
 
CPU Scheduling Algorithms
CPU Scheduling AlgorithmsCPU Scheduling Algorithms
CPU Scheduling Algorithms
 

Semelhante a Thread (20)

OS Module-2.pptx
OS Module-2.pptxOS Module-2.pptx
OS Module-2.pptx
 
Multi threaded programming
Multi threaded programmingMulti threaded programming
Multi threaded programming
 
4.Process.ppt
4.Process.ppt4.Process.ppt
4.Process.ppt
 
Concept of thread
Concept of threadConcept of thread
Concept of thread
 
Threading.pptx
Threading.pptxThreading.pptx
Threading.pptx
 
Bglrsession4
Bglrsession4Bglrsession4
Bglrsession4
 
Thread
ThreadThread
Thread
 
Thread
ThreadThread
Thread
 
Networking threads
Networking threadsNetworking threads
Networking threads
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threads
 
Sucet os module_2_notes
Sucet os module_2_notesSucet os module_2_notes
Sucet os module_2_notes
 
thread os.pptx
thread os.pptxthread os.pptx
thread os.pptx
 
Thread
ThreadThread
Thread
 
Os
OsOs
Os
 
multi-threading
multi-threadingmulti-threading
multi-threading
 
Threads
ThreadsThreads
Threads
 
Treads
TreadsTreads
Treads
 
4 threads
4 threads4 threads
4 threads
 
Wiki 2
Wiki 2Wiki 2
Wiki 2
 
threads-ppfldkgsh;reghuiregiuhrughet.pptx
threads-ppfldkgsh;reghuiregiuhrughet.pptxthreads-ppfldkgsh;reghuiregiuhrughet.pptx
threads-ppfldkgsh;reghuiregiuhrughet.pptx
 

Mais de Mohd Arif

Bootp and dhcp
Bootp and dhcpBootp and dhcp
Bootp and dhcpMohd Arif
 
Arp and rarp
Arp and rarpArp and rarp
Arp and rarpMohd Arif
 
User datagram protocol
User datagram protocolUser datagram protocol
User datagram protocolMohd Arif
 
Project identification
Project identificationProject identification
Project identificationMohd Arif
 
Project evalaution techniques
Project evalaution techniquesProject evalaution techniques
Project evalaution techniquesMohd Arif
 
Presentation
PresentationPresentation
PresentationMohd Arif
 
Pointers in c
Pointers in cPointers in c
Pointers in cMohd Arif
 
Peer to-peer
Peer to-peerPeer to-peer
Peer to-peerMohd Arif
 
Overview of current communications systems
Overview of current communications systemsOverview of current communications systems
Overview of current communications systemsMohd Arif
 
Overall 23 11_2007_hdp
Overall 23 11_2007_hdpOverall 23 11_2007_hdp
Overall 23 11_2007_hdpMohd Arif
 
Objectives of budgeting
Objectives of budgetingObjectives of budgeting
Objectives of budgetingMohd Arif
 
Network management
Network managementNetwork management
Network managementMohd Arif
 
Networing basics
Networing basicsNetworing basics
Networing basicsMohd Arif
 
Iris ngx next generation ip based switching platform
Iris ngx next generation ip based switching platformIris ngx next generation ip based switching platform
Iris ngx next generation ip based switching platformMohd Arif
 
Ip sec and ssl
Ip sec and  sslIp sec and  ssl
Ip sec and sslMohd Arif
 
Ip security in i psec
Ip security in i psecIp security in i psec
Ip security in i psecMohd Arif
 
Intro to comp. hardware
Intro to comp. hardwareIntro to comp. hardware
Intro to comp. hardwareMohd Arif
 

Mais de Mohd Arif (20)

Bootp and dhcp
Bootp and dhcpBootp and dhcp
Bootp and dhcp
 
Arp and rarp
Arp and rarpArp and rarp
Arp and rarp
 
User datagram protocol
User datagram protocolUser datagram protocol
User datagram protocol
 
Project identification
Project identificationProject identification
Project identification
 
Project evalaution techniques
Project evalaution techniquesProject evalaution techniques
Project evalaution techniques
 
Presentation
PresentationPresentation
Presentation
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Peer to-peer
Peer to-peerPeer to-peer
Peer to-peer
 
Overview of current communications systems
Overview of current communications systemsOverview of current communications systems
Overview of current communications systems
 
Overall 23 11_2007_hdp
Overall 23 11_2007_hdpOverall 23 11_2007_hdp
Overall 23 11_2007_hdp
 
Objectives of budgeting
Objectives of budgetingObjectives of budgeting
Objectives of budgeting
 
Network management
Network managementNetwork management
Network management
 
Networing basics
Networing basicsNetworing basics
Networing basics
 
Loaders
LoadersLoaders
Loaders
 
Lists
ListsLists
Lists
 
Iris ngx next generation ip based switching platform
Iris ngx next generation ip based switching platformIris ngx next generation ip based switching platform
Iris ngx next generation ip based switching platform
 
Ip sec and ssl
Ip sec and  sslIp sec and  ssl
Ip sec and ssl
 
Ip security in i psec
Ip security in i psecIp security in i psec
Ip security in i psec
 
Intro to comp. hardware
Intro to comp. hardwareIntro to comp. hardware
Intro to comp. hardware
 
Heap sort
Heap sortHeap sort
Heap sort
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 

Último (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

Thread

  • 1. Part II Process Management Chapter 4: Threads 1
  • 2. What Is a Thread? § A thread, also known as lightweight process (LWP), is a basic unit of CPU execution. § A thread has a thread ID, a program counter, a register set, and a stack. Thus, it is similar to a process has. § However, a thread shares with other threads in the same process its code section, data section, and other OS resources (e.g., files and signals). § A process, or heavyweight process, has a single thread of control. 2
  • 3. Single Threaded and Multithreaded Process Single-threaded process Multithreaded Process 3
  • 4. Benefits of Using Threads § Responsiveness: Other parts (i.e., threads) of a program may still be running even if one part (e.g., a thread) is blocked. § Resource Sharing: Threads of a process, by default, share many system resources (e.g., files and memory). § Economy: Creating and terminating processes, allocating memory and resources, and context switching processes are very time consuming. § Utilization of Multiprocessor Architecture: Multiple CPUs can run multiple threads of the same process. No program change is necessary. 4
  • 5. User and Kernel Threads: 1/3 q User Threads: vUser threads are supported at the user level. The kernel is not aware of user threads. vA library provides all support for thread creation, termination, joining, and scheduling. vThere is no kernel intervention, and, hence, user threads are usually more efficient. vUnfortunately, since the kernel only recognizes the containing process (of the threads), if one thread is blocked, every other threads of the same process are also blocked because the containing process is blocked. 5
  • 6. User and Kernel Threads: 2/3 qKernel threads: vKernel threads are directly supported by the kernel. The kernel does thread creation, termination, joining, and scheduling in kernel space. vKernel threads are usually slower than the user threads. vHowever, blocking one thread will not cause other threads of the same process to block. The kernel simply runs other threads. vIn a multiprocessor environment, the kernel can schedule threads on different processors. 6
  • 7. User and Kernel Threads: 3/3 7
  • 8. Multithreading Models qDifferent systems support threads in different ways. Here are three commonly seen thread models: vMany-to-One Model:One kernel thread (or process) has multiple user threads. Thus, this is a user thread model. vOne-to-One Model: one user thread maps to one kernel thread (e.g., Linux and Windows). vMany-to-Many Model: Multiple user threads maps to a number of kernel threads. 8
  • 10. One-to-One Model: 1/2 An Extreme Case: Traditional Unix 10
  • 13. Thread Issues § How Does a Thread Fork? § Thread Cancellation § Signal Handling § Thread-Specific Data § What Is Thread-Safe? 13
  • 14. How Does a Thread Fork? qIf a thread forks, does the new process: vduplicate all threads? vcontain only the forking thread (i.e., single- threaded)? qSome systems have two fork system calls, one for each case. 14
  • 15. Thread Cancellation: 1/2 qThread cancellation means terminating a thread before it has completed. The thread that is to be cancelled is the target thread. qThere are two types: vAsynchronous Cancellation: the target thread terminates immediately. vDeferred Cancellation: The target thread can periodically check if it should terminate, allowing the target thread an opportunity to terminate itself in an orderly fashion. The point a thread can terminate itself is a cancellation point. 15
  • 16. Thread Cancellation: 2/2 qProblem: With asynchronous cancellation, if the target thread owns some system-wide resources, the system may not be able to reclaim all recourses owned by the target thread. qWith deferred cancellation, the target thread determines the time to terminate itself. Reclaiming resources is not a problem. qMost systems implement asynchronous cancellation for processes (e.g., use the kill system call) and threads. qPthread supports deferred cancellation. 16
  • 17. Signal Handling § Signals is a way the OS uses to notify a process that some event has happened. § Once a signal occurs, who is going to handle it? The process, or one of the threads? § This is a very complex issue and will be discussed later in this course. 17
  • 18. Thread-Specific Data/Thread-Safe qData that a thread needs for its own operation are thread-specific. qPoor support for thread-specific data could cause problem. For example, while threads have their own stacks, they share the heap. qWhat if two malloc() or new are executed at the same time requesting for memory from the heap? Or, two printf or cout are run simultaneously? qIf a library can be used by multiple threads properly, it is a thread-safe one. 18
  • 19. Thread Pool qWhile we know that managing threads are more efficient than managing processes, creating and terminating threads are still not free. qAfter a process is created, one can immediately create a number of threads and have them waiting. qWhen a new task occurs, one can wake up one of the waiting threads and assign it the work. After this thread completes the task, it goes back to wait. qIn this way, we save the number of thread creation and termination. qThese threads are said in a thread pool. 19