SlideShare uma empresa Scribd logo
1 de 40
Baixar para ler offline
OPERATING SYSTEM
Chapter 4: Threads
Chapter 4: Threads
•
•
•
•
•
•
•

Overview
Multicore Programming
Multithreading Models
Thread Libraries
Implicit Threading
Threading Issues
Operating System Examples
Objectives
• To introduce the notion of a thread—a fundamental unit of CPU utilization
that forms the basis of multithreaded computer systems
• To discuss the APIs for the Pthreads, Windows, and Java thread libraries
• To explore several strategies that provide implicit threading
• To examine issues related to multithreaded programming
• To cover operating system support for threads in Windows and Linux
Motivation
•
•
•

Most modern applications are multithreaded
Threads run within application
Multiple tasks with the application can be implemented by separate threads
–
–
–
–

•
•
•

Update display
Fetch data
Spell checking
Answer a network request

Process creation is heavy-weight while thread creation is light-weight
Can simplify code, increase efficiency
Kernels are generally multithreaded
Multithreaded Server Architecture
Benefits
• Responsiveness – may allow continued execution if part of process is
blocked, especially important for user interfaces

• Resource Sharing – threads share resources of process, easier than
shared memory or message passing
• Economy – cheaper than process creation, thread switching lower
overhead than context switching
• Scalability – process can take advantage of multiprocessor architectures
Multicore Programming
•

Multicore or multiprocessor systems putting pressure on programmers, challenges
include:
–
–
–
–
–

•
•
•

Dividing activities
Balance
Data splitting
Data dependency
Testing and debugging

Parallelism implies a system can perform more than one task simultaneously
Concurrency supports more than one task making progress
Single processor / core, scheduler providing concurrency
Multicore Programming (Cont.)
Types of parallelism
•

•

•
•
•

Data parallelism – distributes subsets of the same data across multiple cores, same
operation on each
Task parallelism – distributing threads across cores, each thread performing unique
operation
As # of threads grows, so does architectural support for threading
CPUs have cores as well as hardware threads
Consider Oracle SPARC T4 with 8 cores, and 8 hardware threads per core
Concurrency vs. Parallelism
• Concurrent execution on single-core system:

• Parallelism on a multi-core system:
Single and Multithreaded Processes
Amdahl’s Law
• Identifies performance gains from adding additional cores to an
application that has both serial and parallel components
• S is serial portion
• N processing cores
Amdahl’s Law (Cont.)
• I.e. if application is 75% parallel / 25% serial, moving from 1 to 2
cores results in speedup of 1.6 times
• As N approaches infinity, speedup approaches 1 / S
Serial portion of an application has disproportionate effect on
performance gained by adding additional cores
• But does the law take into account contemporary multicore
systems?
User Threads and Kernel Threads
• User threads - management done by user-level threads
library
• Three primary thread libraries:
– POSIX Pthreads
– Win32 threads
– Java threads
User Threads and Kernel Threads
• Kernel threads - Supported by the Kernel
• Examples – virtually all general purpose operating systems,
including:
–
–
–
–
–

Windows
Solaris
Linux
Tru64 UNIX
Mac OS X
Multithreading Models
• Many-to-One

• One-to-One
• Many-to-Many
Many-to-One
• Many user-level threads mapped
to single kernel thread
• One thread blocking causes all to
block
• Multiple threads may not run in
parallel on muticore system
because only one may be in kernel
at a time
• Examples:
– Solaris Green Threads
– GNU Portable Threads
One-to-One
•
•
•
•

Each user-level thread maps to kernel thread
Creating a user-level thread creates a kernel thread
More concurrency than many-to-one
Number of threads per process sometimes restricted due to overhead

• Examples
– Windows NT/XP/2000
– Linux
– Solaris 9 and later
Many-to-Many Model
• Allows many user level threads to be
mapped to many kernel threads
• Allows the operating system to create a
sufficient number of kernel threads

• Solaris prior to version 9
• Windows NT/2000 with the ThreadFiber
package
Two-level Model
• Similar to M:M, except that it allows a user thread to be
bound to kernel thread
• Examples
–
–
–
–

IRIX
HP-UX
Tru64 UNIX
Solaris 8 and earlier
Thread Libraries
• Thread library provides programmer with API for creating
and managing threads
• Two primary ways of implementing
– Library entirely in user space
– Kernel-level library supported by the OS
Pthreads
• May be provided either as user-level or kernel-level
• A POSIX standard (IEEE 1003.1c) API for thread creation and
synchronization
• Specification, not implementation
• API specifies behavior of the thread library, implementation is up to
development of the library
• Common in UNIX operating systems (Solaris, Linux, Mac OS X)
Java Threads
• Java threads are managed by the JVM
• Typically implemented using the threads model provided by
underlying OS

• Java threads may be created by:
Extending Thread class
– Implementing the Runnable interface
Java Multithreaded Program
Java Multithreaded Program (Cont.)
Implicit Threading
• Growing in popularity as numbers of threads increase, program
correctness more difficult with explicit threads
• Creation and management of threads done by compilers and run-time
libraries rather than programmers
• Three methods explored
– Thread Pools
– OpenMP
– Grand Central Dispatch

• Other methods include Microsoft Threading Building Blocks (TBB),
java.util.concurrent package.
Threading Issues
• Semantics of fork() and exec() system calls
• Signal handling
– Synchronous and asynchronous

• Thread cancellation of target thread
– Asynchronous or deferred

• Thread-local storage
• Scheduler Activations
Semantics of fork() and exec()
• Does fork()duplicate only the calling thread or all
threads?
– Some UNIXes have two versions of fork

• Exec() usually works as normal – replace the running
process including all threads
Signal Handling
• Signals are used in UNIX systems to notify a process that a
particular event has occurred.
• A signal handler is used to process signals
1. Signal is generated by particular event
2. Signal is delivered to a process
3. Signal is handled by one of two signal handlers:
• default
• user-defined
Signal Handling (Cont.)
• Every signal has default handler that kernel runs when handling
signal
– User-defined signal handler can override default
– For single-threaded, signal delivered to process

• Where should a signal be delivered for multi-threaded?
–
–
–
–

Deliver the signal to the thread to which the signal applies
Deliver the signal to every thread in the process
Deliver the signal to certain threads in the process
Assign a specific thread to receive all signals for the process
Thread Cancellation
• Terminating a thread before it has finished
• Thread to be canceled is target thread
• Two general approaches:
– Asynchronous cancellation terminates the target thread immediately
– Deferred cancellation allows the target thread to periodically check if it should be
cancelled

• Pthread code to create and cancel a thread:
Thread Cancellation (Cont.)
• Invoking thread cancellation requests cancellation, but actual cancellation
depends on thread state

• If thread has cancellation disabled, cancellation remains pending until
thread enables it
• Default type is deferred
– Cancellation only occurs when thread reaches cancellation point
• i.e. pthread_testcancel()

• Then cleanup handler is invoked

• On Linux systems, thread cancellation is handled through signals
Thread-Local Storage
• Thread-local storage (TLS) allows each thread to have its own copy of data
• Useful when you do not have control over the thread creation process (i.e.,
when using a thread pool)
• Different from local variables
– Local variables visible only during single function invocation
– TLS visible across function invocations

• Similar to static data
– TLS is unique to each thread
Scheduler Activations
• Both M:M and Two-level models require
communication to maintain the appropriate
number of kernel threads allocated to the
application
• Typically use an intermediate data structure
between user and kernel threads – lightweight
process (LWP)
– Appears to be a virtual processor on which process
can schedule user thread to run
– Each LWP attached to kernel thread
– How many LWPs to create?
Scheduler Activations (Cont.)
• Scheduler activations provide upcalls, a communication mechanism from
the kernel to the upcall handler in the thread library
• This communication allows an application to maintain the correct number
kernel threads
Operating System Examples
• Windows XP Threads

• Linux Thread
Windows Threads
• Windows implements the Windows API – primary API for Win 98, Win NT,
Win 2000, Win XP, and Win 7
• Implements the one-to-one mapping, kernel-level
• Each thread contains
– A thread id
– Register set representing state of processor
– Separate user and kernel stacks for when thread runs in user mode or kernel
mode
– Private data storage area used by run-time libraries and dynamic link libraries
(DLLs)
Windows Threads (Cont.)
• The register set, stacks, and private storage area are known as the context
of the thread
• The primary data structures of a thread include:
– ETHREAD (executive thread block) – includes pointer to process to which thread
belongs and to KTHREAD, in kernel space
– KTHREAD (kernel thread block) – scheduling and synchronization info, kernelmode stack, pointer to TEB, in kernel space
– TEB (thread environment block) – thread id, user-mode stack, thread-local
storage, in user space
Windows XP Threads Data Structures
Linux Threads
• Linux refers to them as tasks rather than threads
• Thread creation is done through clone() system call
• clone() allows a child task to share the address space of the
parent task (process)
– Flags control behavior

• struct task_struct points to process data structures
(shared or unique)
End of Chapter 4

Mais conteúdo relacionado

Mais procurados

Multi threaded programming
Multi threaded programmingMulti threaded programming
Multi threaded programmingAnyapuPranav
 
The Meteor Framework
The Meteor FrameworkThe Meteor Framework
The Meteor FrameworkDamien Magoni
 
OSI Model Layers and Internet Protocol Stack
OSI Model Layers and Internet Protocol StackOSI Model Layers and Internet Protocol Stack
OSI Model Layers and Internet Protocol StackShivam Mitra
 
18 parallel processing
18 parallel processing18 parallel processing
18 parallel processingdilip kumar
 
Bluetooth and Raspberry Pi
Bluetooth and Raspberry PiBluetooth and Raspberry Pi
Bluetooth and Raspberry PiDamien Magoni
 
Advanced computer architecture lesson 5 and 6
Advanced computer architecture lesson 5 and 6Advanced computer architecture lesson 5 and 6
Advanced computer architecture lesson 5 and 6Ismail Mukiibi
 
chap 18 multicore computers
chap 18 multicore computers chap 18 multicore computers
chap 18 multicore computers Sher Shah Merkhel
 
Ch 2: TCP/IP Concepts Review
Ch 2: TCP/IP Concepts ReviewCh 2: TCP/IP Concepts Review
Ch 2: TCP/IP Concepts ReviewSam Bowne
 
seL4 on RISC-V/lowRISC - ORCONF'15
seL4 on RISC-V/lowRISC - ORCONF'15seL4 on RISC-V/lowRISC - ORCONF'15
seL4 on RISC-V/lowRISC - ORCONF'15Hesham Almatary
 

Mais procurados (20)

Multi threaded programming
Multi threaded programmingMulti threaded programming
Multi threaded programming
 
The Meteor Framework
The Meteor FrameworkThe Meteor Framework
The Meteor Framework
 
14 superscalar
14 superscalar14 superscalar
14 superscalar
 
OSI Model Layers and Internet Protocol Stack
OSI Model Layers and Internet Protocol StackOSI Model Layers and Internet Protocol Stack
OSI Model Layers and Internet Protocol Stack
 
18 parallel processing
18 parallel processing18 parallel processing
18 parallel processing
 
Bluetooth and Raspberry Pi
Bluetooth and Raspberry PiBluetooth and Raspberry Pi
Bluetooth and Raspberry Pi
 
Advanced computer architecture lesson 5 and 6
Advanced computer architecture lesson 5 and 6Advanced computer architecture lesson 5 and 6
Advanced computer architecture lesson 5 and 6
 
Chapter11
Chapter11Chapter11
Chapter11
 
chap 18 multicore computers
chap 18 multicore computers chap 18 multicore computers
chap 18 multicore computers
 
Thread
ThreadThread
Thread
 
VLIW Processors
VLIW ProcessorsVLIW Processors
VLIW Processors
 
Ch 2: TCP/IP Concepts Review
Ch 2: TCP/IP Concepts ReviewCh 2: TCP/IP Concepts Review
Ch 2: TCP/IP Concepts Review
 
13 risc
13 risc13 risc
13 risc
 
27 multicore
27 multicore27 multicore
27 multicore
 
07 input output
07 input output07 input output
07 input output
 
seL4 on RISC-V/lowRISC - ORCONF'15
seL4 on RISC-V/lowRISC - ORCONF'15seL4 on RISC-V/lowRISC - ORCONF'15
seL4 on RISC-V/lowRISC - ORCONF'15
 
Section04 threads
Section04 threadsSection04 threads
Section04 threads
 
10. compute-part-1
10. compute-part-110. compute-part-1
10. compute-part-1
 
IPv6 Transition Considerations for ISPs
IPv6 Transition Considerations for ISPsIPv6 Transition Considerations for ISPs
IPv6 Transition Considerations for ISPs
 
08. networking
08. networking08. networking
08. networking
 

Destaque (17)

Ch5
Ch5Ch5
Ch5
 
Ch5 process synchronization
Ch5   process synchronizationCh5   process synchronization
Ch5 process synchronization
 
Ch7
Ch7Ch7
Ch7
 
Ch21
Ch21Ch21
Ch21
 
Rekayasa perankat lunak jilit 1
Rekayasa perankat lunak jilit 1Rekayasa perankat lunak jilit 1
Rekayasa perankat lunak jilit 1
 
Ch10 file system interface
Ch10   file system interfaceCh10   file system interface
Ch10 file system interface
 
E3 chap-01
E3 chap-01E3 chap-01
E3 chap-01
 
E3 chap-02
E3 chap-02E3 chap-02
E3 chap-02
 
E3 chap-16
E3 chap-16E3 chap-16
E3 chap-16
 
Ch13
Ch13Ch13
Ch13
 
Presentasi Pemrograman Berbasis Objek
Presentasi Pemrograman Berbasis ObjekPresentasi Pemrograman Berbasis Objek
Presentasi Pemrograman Berbasis Objek
 
E3 chap-08
E3 chap-08E3 chap-08
E3 chap-08
 
E3 chap-21
E3 chap-21E3 chap-21
E3 chap-21
 
Ch8
Ch8Ch8
Ch8
 
Hci [5]paradigm
Hci [5]paradigmHci [5]paradigm
Hci [5]paradigm
 
Peluang bersyarat
Peluang bersyaratPeluang bersyarat
Peluang bersyarat
 
E3 chap-13
E3 chap-13E3 chap-13
E3 chap-13
 

Semelhante a Ch4 threads

Module2 MultiThreads.ppt
Module2 MultiThreads.pptModule2 MultiThreads.ppt
Module2 MultiThreads.pptshreesha16
 
Multithreaded Programming Part- II.pdf
Multithreaded Programming Part- II.pdfMultithreaded Programming Part- II.pdf
Multithreaded Programming Part- II.pdfHarika Pudugosula
 
Multithreaded Programming Part- III.pdf
Multithreaded Programming Part- III.pdfMultithreaded Programming Part- III.pdf
Multithreaded Programming Part- III.pdfHarika Pudugosula
 
OS Module-2.pptx
OS Module-2.pptxOS Module-2.pptx
OS Module-2.pptxbleh23
 
Operating system 22 threading issues
Operating system 22 threading issuesOperating system 22 threading issues
Operating system 22 threading issuesVaibhav Khanna
 
Operating system 20 threads
Operating system 20 threadsOperating system 20 threads
Operating system 20 threadsVaibhav Khanna
 
Lecture 3- Threads (1).pptx
Lecture 3- Threads (1).pptxLecture 3- Threads (1).pptx
Lecture 3- Threads (1).pptxAmanuelmergia
 
chapter4-processes nd processors in DS.ppt
chapter4-processes nd processors in DS.pptchapter4-processes nd processors in DS.ppt
chapter4-processes nd processors in DS.pptaakarshsiwani1
 
Operating system 21 multithreading models
Operating system 21 multithreading modelsOperating system 21 multithreading models
Operating system 21 multithreading modelsVaibhav Khanna
 
Multithreading models
Multithreading modelsMultithreading models
Multithreading modelsanoopkrishna2
 
VTU 6th Sem Elective CSE - Module 3 cloud computing
VTU 6th Sem Elective CSE - Module 3 cloud computingVTU 6th Sem Elective CSE - Module 3 cloud computing
VTU 6th Sem Elective CSE - Module 3 cloud computingSachin Gowda
 
Processes and Threads in Windows Vista
Processes and Threads in Windows VistaProcesses and Threads in Windows Vista
Processes and Threads in Windows VistaTrinh Phuc Tho
 

Semelhante a Ch4 threads (20)

4 threads
4 threads4 threads
4 threads
 
Module2 MultiThreads.ppt
Module2 MultiThreads.pptModule2 MultiThreads.ppt
Module2 MultiThreads.ppt
 
Multithreaded Programming Part- II.pdf
Multithreaded Programming Part- II.pdfMultithreaded Programming Part- II.pdf
Multithreaded Programming Part- II.pdf
 
Multithreaded Programming Part- III.pdf
Multithreaded Programming Part- III.pdfMultithreaded Programming Part- III.pdf
Multithreaded Programming Part- III.pdf
 
OS Module-2.pptx
OS Module-2.pptxOS Module-2.pptx
OS Module-2.pptx
 
Operating system 22 threading issues
Operating system 22 threading issuesOperating system 22 threading issues
Operating system 22 threading issues
 
Threads.ppt
Threads.pptThreads.ppt
Threads.ppt
 
Operating system 20 threads
Operating system 20 threadsOperating system 20 threads
Operating system 20 threads
 
Thread
ThreadThread
Thread
 
Thread
ThreadThread
Thread
 
Lecture 3- Threads (1).pptx
Lecture 3- Threads (1).pptxLecture 3- Threads (1).pptx
Lecture 3- Threads (1).pptx
 
CH04.pdf
CH04.pdfCH04.pdf
CH04.pdf
 
chapter4-processes nd processors in DS.ppt
chapter4-processes nd processors in DS.pptchapter4-processes nd processors in DS.ppt
chapter4-processes nd processors in DS.ppt
 
OS Thr schd.ppt
OS Thr schd.pptOS Thr schd.ppt
OS Thr schd.ppt
 
Lecture 3 threads
Lecture 3   threadsLecture 3   threads
Lecture 3 threads
 
Pthread
PthreadPthread
Pthread
 
Operating system 21 multithreading models
Operating system 21 multithreading modelsOperating system 21 multithreading models
Operating system 21 multithreading models
 
Multithreading models
Multithreading modelsMultithreading models
Multithreading models
 
VTU 6th Sem Elective CSE - Module 3 cloud computing
VTU 6th Sem Elective CSE - Module 3 cloud computingVTU 6th Sem Elective CSE - Module 3 cloud computing
VTU 6th Sem Elective CSE - Module 3 cloud computing
 
Processes and Threads in Windows Vista
Processes and Threads in Windows VistaProcesses and Threads in Windows Vista
Processes and Threads in Windows Vista
 

Último

Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 

Último (20)

Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 

Ch4 threads

  • 2. Chapter 4: Threads • • • • • • • Overview Multicore Programming Multithreading Models Thread Libraries Implicit Threading Threading Issues Operating System Examples
  • 3. Objectives • To introduce the notion of a thread—a fundamental unit of CPU utilization that forms the basis of multithreaded computer systems • To discuss the APIs for the Pthreads, Windows, and Java thread libraries • To explore several strategies that provide implicit threading • To examine issues related to multithreaded programming • To cover operating system support for threads in Windows and Linux
  • 4. Motivation • • • Most modern applications are multithreaded Threads run within application Multiple tasks with the application can be implemented by separate threads – – – – • • • Update display Fetch data Spell checking Answer a network request Process creation is heavy-weight while thread creation is light-weight Can simplify code, increase efficiency Kernels are generally multithreaded
  • 6. Benefits • Responsiveness – may allow continued execution if part of process is blocked, especially important for user interfaces • Resource Sharing – threads share resources of process, easier than shared memory or message passing • Economy – cheaper than process creation, thread switching lower overhead than context switching • Scalability – process can take advantage of multiprocessor architectures
  • 7. Multicore Programming • Multicore or multiprocessor systems putting pressure on programmers, challenges include: – – – – – • • • Dividing activities Balance Data splitting Data dependency Testing and debugging Parallelism implies a system can perform more than one task simultaneously Concurrency supports more than one task making progress Single processor / core, scheduler providing concurrency
  • 8. Multicore Programming (Cont.) Types of parallelism • • • • • Data parallelism – distributes subsets of the same data across multiple cores, same operation on each Task parallelism – distributing threads across cores, each thread performing unique operation As # of threads grows, so does architectural support for threading CPUs have cores as well as hardware threads Consider Oracle SPARC T4 with 8 cores, and 8 hardware threads per core
  • 9. Concurrency vs. Parallelism • Concurrent execution on single-core system: • Parallelism on a multi-core system:
  • 11. Amdahl’s Law • Identifies performance gains from adding additional cores to an application that has both serial and parallel components • S is serial portion • N processing cores
  • 12. Amdahl’s Law (Cont.) • I.e. if application is 75% parallel / 25% serial, moving from 1 to 2 cores results in speedup of 1.6 times • As N approaches infinity, speedup approaches 1 / S Serial portion of an application has disproportionate effect on performance gained by adding additional cores • But does the law take into account contemporary multicore systems?
  • 13. User Threads and Kernel Threads • User threads - management done by user-level threads library • Three primary thread libraries: – POSIX Pthreads – Win32 threads – Java threads
  • 14. User Threads and Kernel Threads • Kernel threads - Supported by the Kernel • Examples – virtually all general purpose operating systems, including: – – – – – Windows Solaris Linux Tru64 UNIX Mac OS X
  • 15. Multithreading Models • Many-to-One • One-to-One • Many-to-Many
  • 16. Many-to-One • Many user-level threads mapped to single kernel thread • One thread blocking causes all to block • Multiple threads may not run in parallel on muticore system because only one may be in kernel at a time • Examples: – Solaris Green Threads – GNU Portable Threads
  • 17. One-to-One • • • • Each user-level thread maps to kernel thread Creating a user-level thread creates a kernel thread More concurrency than many-to-one Number of threads per process sometimes restricted due to overhead • Examples – Windows NT/XP/2000 – Linux – Solaris 9 and later
  • 18. Many-to-Many Model • Allows many user level threads to be mapped to many kernel threads • Allows the operating system to create a sufficient number of kernel threads • Solaris prior to version 9 • Windows NT/2000 with the ThreadFiber package
  • 19. Two-level Model • Similar to M:M, except that it allows a user thread to be bound to kernel thread • Examples – – – – IRIX HP-UX Tru64 UNIX Solaris 8 and earlier
  • 20. Thread Libraries • Thread library provides programmer with API for creating and managing threads • Two primary ways of implementing – Library entirely in user space – Kernel-level library supported by the OS
  • 21. Pthreads • May be provided either as user-level or kernel-level • A POSIX standard (IEEE 1003.1c) API for thread creation and synchronization • Specification, not implementation • API specifies behavior of the thread library, implementation is up to development of the library • Common in UNIX operating systems (Solaris, Linux, Mac OS X)
  • 22. Java Threads • Java threads are managed by the JVM • Typically implemented using the threads model provided by underlying OS • Java threads may be created by: Extending Thread class – Implementing the Runnable interface
  • 25. Implicit Threading • Growing in popularity as numbers of threads increase, program correctness more difficult with explicit threads • Creation and management of threads done by compilers and run-time libraries rather than programmers • Three methods explored – Thread Pools – OpenMP – Grand Central Dispatch • Other methods include Microsoft Threading Building Blocks (TBB), java.util.concurrent package.
  • 26. Threading Issues • Semantics of fork() and exec() system calls • Signal handling – Synchronous and asynchronous • Thread cancellation of target thread – Asynchronous or deferred • Thread-local storage • Scheduler Activations
  • 27. Semantics of fork() and exec() • Does fork()duplicate only the calling thread or all threads? – Some UNIXes have two versions of fork • Exec() usually works as normal – replace the running process including all threads
  • 28. Signal Handling • Signals are used in UNIX systems to notify a process that a particular event has occurred. • A signal handler is used to process signals 1. Signal is generated by particular event 2. Signal is delivered to a process 3. Signal is handled by one of two signal handlers: • default • user-defined
  • 29. Signal Handling (Cont.) • Every signal has default handler that kernel runs when handling signal – User-defined signal handler can override default – For single-threaded, signal delivered to process • Where should a signal be delivered for multi-threaded? – – – – Deliver the signal to the thread to which the signal applies Deliver the signal to every thread in the process Deliver the signal to certain threads in the process Assign a specific thread to receive all signals for the process
  • 30. Thread Cancellation • Terminating a thread before it has finished • Thread to be canceled is target thread • Two general approaches: – Asynchronous cancellation terminates the target thread immediately – Deferred cancellation allows the target thread to periodically check if it should be cancelled • Pthread code to create and cancel a thread:
  • 31. Thread Cancellation (Cont.) • Invoking thread cancellation requests cancellation, but actual cancellation depends on thread state • If thread has cancellation disabled, cancellation remains pending until thread enables it • Default type is deferred – Cancellation only occurs when thread reaches cancellation point • i.e. pthread_testcancel() • Then cleanup handler is invoked • On Linux systems, thread cancellation is handled through signals
  • 32. Thread-Local Storage • Thread-local storage (TLS) allows each thread to have its own copy of data • Useful when you do not have control over the thread creation process (i.e., when using a thread pool) • Different from local variables – Local variables visible only during single function invocation – TLS visible across function invocations • Similar to static data – TLS is unique to each thread
  • 33. Scheduler Activations • Both M:M and Two-level models require communication to maintain the appropriate number of kernel threads allocated to the application • Typically use an intermediate data structure between user and kernel threads – lightweight process (LWP) – Appears to be a virtual processor on which process can schedule user thread to run – Each LWP attached to kernel thread – How many LWPs to create?
  • 34. Scheduler Activations (Cont.) • Scheduler activations provide upcalls, a communication mechanism from the kernel to the upcall handler in the thread library • This communication allows an application to maintain the correct number kernel threads
  • 35. Operating System Examples • Windows XP Threads • Linux Thread
  • 36. Windows Threads • Windows implements the Windows API – primary API for Win 98, Win NT, Win 2000, Win XP, and Win 7 • Implements the one-to-one mapping, kernel-level • Each thread contains – A thread id – Register set representing state of processor – Separate user and kernel stacks for when thread runs in user mode or kernel mode – Private data storage area used by run-time libraries and dynamic link libraries (DLLs)
  • 37. Windows Threads (Cont.) • The register set, stacks, and private storage area are known as the context of the thread • The primary data structures of a thread include: – ETHREAD (executive thread block) – includes pointer to process to which thread belongs and to KTHREAD, in kernel space – KTHREAD (kernel thread block) – scheduling and synchronization info, kernelmode stack, pointer to TEB, in kernel space – TEB (thread environment block) – thread id, user-mode stack, thread-local storage, in user space
  • 38. Windows XP Threads Data Structures
  • 39. Linux Threads • Linux refers to them as tasks rather than threads • Thread creation is done through clone() system call • clone() allows a child task to share the address space of the parent task (process) – Flags control behavior • struct task_struct points to process data structures (shared or unique)