SlideShare a Scribd company logo
1 of 374
Download to read offline
Chapter 1: Introduction
Chapter 1: Introduction
1.2 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Chapter 1: Introduction
Chapter 1: Introduction
„ What Operating Systems Do
„ Computer-System Organization
„ Computer-System Architecture
„ Operating-System Structure
„ Operating-System Operations
„ Process Management
„ Memory Management
„ Storage Management
„ Protection and Security
„ Distributed Systems
„ Special-Purpose Systems
„ Computing Environments
1.3 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Objectives
Objectives
„ To provide a grand tour of the major operating systems
components
„ To provide coverage of basic computer system organization
1.4 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
What is an Operating System?
What is an Operating System?
„ A program that acts as an intermediary between a user of a
computer and the computer hardware.
„ Operating system goals:
z Execute user programs and make solving user problems
easier.
z Make the computer system convenient to use.
„ Use the computer hardware in an efficient manner.
1.5 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Computer System Structure
Computer System Structure
„ Computer system can be divided into four components
z Hardware – provides basic computing resources
 CPU, memory, I/O devices
z Operating system
 Controls and coordinates use of hardware among various
applications and users
z Application programs – define the ways in which the system
resources are used to solve the computing problems of the
users
 Word processors, compilers, web browsers, database
systems, video games
z Users
 People, machines, other computers
1.6 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Four Components of a Computer System
Four Components of a Computer System
1.7 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Operating System Definition
Operating System Definition
„ OS is a resource allocator
z Manages all resources
z Decides between conflicting requests for efficient and fair
resource use
„ OS is a control program
z Controls execution of programs to prevent errors and improper
use of the computer
1.8 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Operating System Definition (Cont.)
Operating System Definition (Cont.)
„ No universally accepted definition
„ “Everything a vendor ships when you order an operating system”
is good approximation
z But varies wildly
„ “The one program running at all times on the computer” is the
kernel. Everything else is either a system program (ships with
the operating system) or an application program
1.9 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Computer Startup
Computer Startup
„ bootstrap program is loaded at power-up or reboot
z Typically stored in ROM or EPROM, generally known as
firmware
z Initializates all aspects of system
z Loads operating system kernel and starts execution
1.10 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Computer System Organization
Computer System Organization
„ Computer-system operation
z One or more CPUs, device controllers connect through
common bus providing access to shared memory
z Concurrent execution of CPUs and devices competing for
memory cycles
1.11 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Computer
Computer-
-System Operation
System Operation
„ I/O devices and the CPU can execute concurrently.
„ Each device controller is in charge of a particular device type.
„ Each device controller has a local buffer.
„ CPU moves data from/to main memory to/from local buffers
„ I/O is from the device to local buffer of controller.
„ Device controller informs CPU that it has finished its operation by
causing an interrupt.
1.12 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Common Functions of Interrupts
Common Functions of Interrupts
„ Interrupt transfers control to the interrupt service routine generally,
through the interrupt vector, which contains the addresses of all the
service routines.
„ Interrupt architecture must save the address of the interrupted
instruction.
„ Incoming interrupts are disabled while another interrupt is being
processed to prevent a lost interrupt.
„ A trap is a software-generated interrupt caused either by an error
or a user request.
„ An operating system is interrupt driven.
1.13 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Interrupt Handling
Interrupt Handling
„ The operating system preserves the state of the CPU by storing
registers and the program counter.
„ Determines which type of interrupt has occurred:
z polling
z vectored interrupt system
„ Separate segments of code determine what action should be taken
for each type of interrupt
1.14 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Interrupt Timeline
Interrupt Timeline
1.15 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
I/O Structure
I/O Structure
„ After I/O starts, control returns to user program only upon I/O
completion.
z Wait instruction idles the CPU until the next interrupt
z Wait loop (contention for memory access).
z At most one I/O request is outstanding at a time, no
simultaneous I/O processing.
„ After I/O starts, control returns to user program without waiting
for I/O completion.
z System call – request to the operating system to allow user
to wait for I/O completion.
z Device-status table contains entry for each I/O device
indicating its type, address, and state.
z Operating system indexes into I/O device table to determine
device status and to modify table entry to include interrupt.
1.16 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Two I/O Methods
Two I/O Methods
Synchronous Asynchronous
1.17 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Device
Device-
-Status Table
Status Table
1.18 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Direct Memory Access Structure
Direct Memory Access Structure
„ Used for high-speed I/O devices able to transmit information at
close to memory speeds.
„ Device controller transfers blocks of data from buffer storage
directly to main memory without CPU intervention.
„ Only one interrupt is generated per block, rather than the one
interrupt per byte.
1.19 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Storage Structure
Storage Structure
„ Main memory – only large storage media that the CPU can access
directly.
„ Secondary storage – extension of main memory that provides large
nonvolatile storage capacity.
„ Magnetic disks – rigid metal or glass platters covered with
magnetic recording material
z Disk surface is logically divided into tracks, which are
subdivided into sectors.
z The disk controller determines the logical interaction between
the device and the computer.
1.20 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Storage Hierarchy
Storage Hierarchy
„ Storage systems organized in hierarchy.
z Speed
z Cost
z Volatility
„ Caching – copying information into faster storage system; main
memory can be viewed as a last cache for secondary storage.
1.21 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Storage
Storage-
-Device Hierarchy
Device Hierarchy
1.22 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Caching
Caching
„ Important principle, performed at many levels in a computer (in
hardware, operating system, software)
„ Information in use copied from slower to faster storage temporarily
„ Faster storage (cache) checked first to determine if information is
there
z If it is, information used directly from the cache (fast)
z If not, data copied to cache and used there
„ Cache smaller than storage being cached
z Cache management important design problem
z Cache size and replacement policy
1.23 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Performance of Various Levels of Storage
Performance of Various Levels of Storage
„ Movement between levels of storage hierarchy can be explicit or
implicit
1.24 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Migration of Integer A from Disk to Register
Migration of Integer A from Disk to Register
„ Multitasking environments must be careful to use most recent
value, no matter where it is stored in the storage hierarchy
„ Multiprocessor environment must provide cache coherency in
hardware such that all CPUs have the most recent value in their
cache
„ Distributed environment situation even more complex
z Several copies of a datum can exist
z Various solutions covered in Chapter 17
1.25 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Operating System Structure
Operating System Structure
„ Multiprogramming needed for efficiency
z Single user cannot keep CPU and I/O devices busy at all times
z Multiprogramming organizes jobs (code and data) so CPU always has
one to execute
z A subset of total jobs in system is kept in memory
z One job selected and run via job scheduling
z When it has to wait (for I/O for example), OS switches to another job
„ Timesharing (multitasking) is logical extension in which CPU switches jobs
so frequently that users can interact with each job while it is running,
creating interactive computing
z Response time should be  1 second
z Each user has at least one program executing in memory process
z If several jobs ready to run at the same time  CPU scheduling
z If processes don’t fit in memory, swapping moves them in and out to
run
z Virtual memory allows execution of processes not completely in
memory
1.26 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Memory Layout for Multiprogrammed System
Memory Layout for Multiprogrammed System
1.27 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Operating
Operating-
-System Operations
System Operations
„ Interrupt driven by hardware
„ Software error or request creates exception or trap
z Division by zero, request for operating system service
„ Other process problems include infinite loop, processes modifying
each other or the operating system
„ Dual-mode operation allows OS to protect itself and other system
components
z User mode and kernel mode
z Mode bit provided by hardware
 Provides ability to distinguish when system is running user
code or kernel code
 Some instructions designated as privileged, only
executable in kernel mode
 System call changes mode to kernel, return from call resets
it to user
1.28 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Transition from User to Kernel Mode
Transition from User to Kernel Mode
„ Timer to prevent infinite loop / process hogging resources
z Set interrupt after specific period
z Operating system decrements counter
z When counter zero generate an interrupt
z Set up before scheduling process to regain control or terminate
program that exceeds allotted time
1.29 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Process Management
Process Management
„ A process is a program in execution. It is a unit of work within the system.
Program is a passive entity, process is an active entity.
„ Process needs resources to accomplish its task
z CPU, memory, I/O, files
z Initialization data
„ Process termination requires reclaim of any reusable resources
„ Single-threaded process has one program counter specifying location of
next instruction to execute
z Process executes instructions sequentially, one at a time, until
completion
„ Multi-threaded process has one program counter per thread
„ Typically system has many processes, some user, some operating system
running concurrently on one or more CPUs
z Concurrency by multiplexing the CPUs among the processes / threads
1.30 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Process Management Activities
Process Management Activities
The operating system is responsible for the following activities in
connection with process management:
„ Creating and deleting both user and system processes
„ Suspending and resuming processes
„ Providing mechanisms for process synchronization
„ Providing mechanisms for process communication
„ Providing mechanisms for deadlock handling
1.31 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Memory Management
Memory Management
„ All data in memory before and after processing
„ All instructions in memory in order to execute
„ Memory management determines what is in memory when
z Optimizing CPU utilization and computer response to users
„ Memory management activities
z Keeping track of which parts of memory are currently being
used and by whom
z Deciding which processes (or parts thereof) and data to move
into and out of memory
z Allocating and deallocating memory space as needed
1.32 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Storage Management
Storage Management
„ OS provides uniform, logical view of information storage
z Abstracts physical properties to logical storage unit - file
z Each medium is controlled by device (i.e., disk drive, tape drive)
 Varying properties include access speed, capacity, data-
transfer rate, access method (sequential or random)
„ File-System management
z Files usually organized into directories
z Access control on most systems to determine who can access
what
z OS activities include
 Creating and deleting files and directories
 Primitives to manipulate files and dirs
 Mapping files onto secondary storage
 Backup files onto stable (non-volatile) storage media
1.33 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Mass
Mass-
-Storage Management
Storage Management
„ Usually disks used to store data that does not fit in main memory or data
that must be kept for a “long” period of time.
„ Proper management is of central importance
„ Entire speed of computer operation hinges on disk subsystem and its
algorithms
„ OS activities
z Free-space management
z Storage allocation
z Disk scheduling
„ Some storage need not be fast
z Tertiary storage includes optical storage, magnetic tape
z Still must be managed
z Varies between WORM (write-once, read-many-times) and RW (read-
write)
1.34 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
I/O Subsystem
I/O Subsystem
„ One purpose of OS is to hide peculiarities of hardware devices
from the user
„ I/O subsystem responsible for
z Memory management of I/O including buffering (storing data
temporarily while it is being transferred), caching (storing parts
of data in faster storage for performance), spooling (the
overlapping of output of one job with input of other jobs)
z General device-driver interface
z Drivers for specific hardware devices
1.35 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Protection and Security
Protection and Security
„ Protection – any mechanism for controlling access of processes or
users to resources defined by the OS
„ Security – defense of the system against internal and external
attacks
z Huge range, including denial-of-service, worms, viruses,
identity theft, theft of service
„ Systems generally first distinguish among users, to determine who
can do what
z User identities (user IDs, security IDs) include name and
associated number, one per user
z User ID then associated with all files, processes of that user to
determine access control
z Group identifier (group ID) allows set of users to be defined
and controls managed, then also associated with each process,
file
z Privilege escalation allows user to change to effective ID with
more rights
1.36 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Computing Environments
Computing Environments
„ Traditional computer
z Blurring over time
z Office environment
 PCs connected to a network, terminals attached to
mainframe or minicomputers providing batch and
timesharing
 Now portals allowing networked and remote systems
access to same resources
z Home networks
 Used to be single system, then modems
 Now firewalled, networked
1.37 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Computing Environments (Cont.)
Computing Environments (Cont.)
„ Client-Server Computing
z Dumb terminals supplanted by smart PCs
z Many systems now servers, responding to requests generated by
clients
 Compute-server provides an interface to client to request
services (i.e. database)
 File-server provides interface for clients to store and retrieve
files
1.38 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Peer
Peer-
-to
to-
-Peer Computing
Peer Computing
„ Another model of distributed system
„ P2P does not distinguish clients and servers
z Instead all nodes are considered peers
z May each act as client, server or both
z Node must join P2P network
 Registers its service with central lookup service on network,
or
 Broadcast request for service and respond to requests for
service via discovery protocol
z Examples include Napster and Gnutella
1.39 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 12, 2005
Web
Web-
-Based Computing
Based Computing
„ Web has become ubiquitous
„ PCs most prevalent devices
„ More devices becoming networked to allow web access
„ New category of devices to manage web traffic among similar
servers: load balancers
„ Use of operating systems like Windows 95, client-side, have
evolved into Linux and Windows XP, which can be clients and
servers
End of Chapter 1
End of Chapter 1
Chapter 2: Operating
Chapter 2: Operating-
-System Structures
System Structures
2.2 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Chapter 2: Operating
Chapter 2: Operating-
-System Structures
System Structures
„ Operating System Services
„ User Operating System Interface
„ System Calls
„ Types of System Calls
„ System Programs
„ Operating System Design and Implementation
„ Operating System Structure
„ Virtual Machines
„ Operating System Generation
„ System Boot
2.3 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Objectives
Objectives
„ To describe the services an operating system provides to users,
processes, and other systems
„ To discuss the various ways of structuring an operating system
„ To explain how operating systems are installed and customized
and how they boot
2.4 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Operating System Services
Operating System Services
„ One set of operating-system services provides functions that are
helpful to the user:
z User interface - Almost all operating systems have a user interface (UI)
 Varies between Command-Line (CLI), Graphics User Interface
(GUI), Batch
z Program execution - The system must be able to load a program into
memory and to run that program, end execution, either normally or
abnormally (indicating error)
z I/O operations - A running program may require I/O, which may involve
a file or an I/O device.
z File-system manipulation - The file system is of particular interest.
Obviously, programs need to read and write files and directories, create
and delete them, search them, list file Information, permission
management.
2.5 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Operating System Services (Cont.)
Operating System Services (Cont.)
„ One set of operating-system services provides functions that are
helpful to the user (Cont):
z Communications – Processes may exchange information, on the same
computer or between computers over a network
 Communications may be via shared memory or through message
passing (packets moved by the OS)
z Error detection – OS needs to be constantly aware of possible errors
 May occur in the CPU and memory hardware, in I/O devices, in user
program
 For each type of error, OS should take the appropriate action to
ensure correct and consistent computing
 Debugging facilities can greatly enhance the user’s and
programmer’s abilities to efficiently use the system
2.6 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Operating System Services (Cont.)
Operating System Services (Cont.)
„ Another set of OS functions exists for ensuring the efficient operation of the
system itself via resource sharing
z Resource allocation - When multiple users or multiple jobs running
concurrently, resources must be allocated to each of them
 Many types of resources - Some (such as CPU cycles,mainmemory,
and file storage) may have special allocation code, others (such as I/O
devices) may have general request and release code.
z Accounting - To keep track of which users use how much and what kinds
of computer resources
z Protection and security - The owners of information stored in a multiuser
or networked computer system may want to control use of that information,
concurrent processes should not interfere with each other
 Protection involves ensuring that all access to system resources is
controlled
 Security of the system from outsiders requires user authentication,
extends to defending external I/O devices from invalid access attempts
 If a system is to be protected and secure, precautions must be
instituted throughout it. A chain is only as strong as its weakest link.
2.7 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
User Operating System Interface
User Operating System Interface -
- CLI
CLI
CLI allows direct command entry
 Sometimes implemented in kernel, sometimes by systems
program
 Sometimes multiple flavors implemented – shells
 Primarily fetches a command from user and executes it
– Sometimes commands built-in, sometimes just names of
programs
» If the latter, adding new features doesn’t require shell
modification
2.8 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
User Operating System Interface
User Operating System Interface -
- GUI
GUI
„ User-friendly desktop metaphor interface
z Usually mouse, keyboard, and monitor
z Icons represent files, programs, actions, etc
z Various mouse buttons over objects in the interface cause
various actions (provide information, options, execute function,
open directory (known as a folder)
z Invented at Xerox PARC
„ Many systems now include both CLI and GUI interfaces
z Microsoft Windows is GUI with CLI “command” shell
z Apple Mac OS X as “Aqua” GUI interface with UNIX kernel
underneath and shells available
z Solaris is CLI with optional GUI interfaces (Java Desktop, KDE)
2.9 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
System Calls
System Calls
„ Programming interface to the services provided by the OS
„ Typically written in a high-level language (C or C++)
„ Mostly accessed by programs via a high-level Application
Program Interface (API) rather than direct system call use
„ Three most common APIs are Win32 API for Windows, POSIX API
for POSIX-based systems (including virtually all versions of UNIX,
Linux, and Mac OS X), and Java API for the Java virtual machine
(JVM)
„ Why use APIs rather than system calls?
(Note that the system-call names used throughout this text are
generic)
2.10 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Example of System Calls
Example of System Calls
„ System call sequence to copy the contents of one file to another file
2.11 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Example of Standard API
Example of Standard API
„ Consider the ReadFile() function in the
„ Win32 API—a function for reading from a file
„ A description of the parameters passed to ReadFile()
z HANDLE file—the file to be read
z LPVOID buffer—a buffer where the data will be read into and written
from
z DWORD bytesToRead—the number of bytes to be read into the buffer
z LPDWORD bytesRead—the number of bytes read during the last read
z LPOVERLAPPED ovl—indicates if overlapped I/O is being used
2.12 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
System Call Implementation
System Call Implementation
„ Typically, a number associated with each system call
z System-call interface maintains a table indexed according to
these numbers
„ The system call interface invokes intended system call in OS kernel
and returns status of the system call and any return values
„ The caller need know nothing about how the system call is
implemented
z Just needs to obey API and understand what OS will do as a
result call
z Most details of OS interface hidden from programmer by API
 Managed by run-time support library (set of functions built
into libraries included with compiler)
2.13 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
API
API –
– System Call
System Call –
– OS Relationship
OS Relationship
2.14 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Standard C Library Example
Standard C Library Example
„ C program invoking printf() library call, which calls write() system call
2.15 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
System Call Parameter Passing
System Call Parameter Passing
„ Often, more information is required than simply identity of desired
system call
z Exact type and amount of information vary according to OS and
call
„ Three general methods used to pass parameters to the OS
z Simplest: pass the parameters in registers
 In some cases, may be more parameters than registers
z Parameters stored in a block, or table, in memory, and address
of block passed as a parameter in a register
 This approach taken by Linux and Solaris
z Parameters placed, or pushed, onto the stack by the program
and popped off the stack by the operating system
z Block and stack methods do not limit the number or length of
parameters being passed
2.16 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Parameter Passing via Table
Parameter Passing via Table
2.17 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Types of System Calls
Types of System Calls
„ Process control
„ File management
„ Device management
„ Information maintenance
„ Communications
2.18 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
MS
MS-
-DOS execution
DOS execution
(a) At system startup (b) running a program
2.19 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
FreeBSD Running Multiple Programs
FreeBSD Running Multiple Programs
2.20 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
System Programs
System Programs
„ System programs provide a convenient environment for program
development and execution. The can be divided into:
z File manipulation
z Status information
z File modification
z Programming language support
z Program loading and execution
z Communications
z Application programs
„ Most users’ view of the operation system is defined by system
programs, not the actual system calls
2.21 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Solaris 10
Solaris 10 dtrace
dtrace Following System Call
Following System Call
2.22 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
System Programs
System Programs
„ Provide a convenient environment for program development and execution
z Some of them are simply user interfaces to system calls; others are
considerably more complex
„ File management - Create, delete, copy, rename, print, dump, list, and
generally manipulate files and directories
„ Status information
z Some ask the system for info - date, time, amount of available memory,
disk space, number of users
z Others provide detailed performance, logging, and debugging
information
z Typically, these programs format and print the output to the terminal or
other output devices
z Some systems implement a registry - used to store and retrieve
configuration information
2.23 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
System Programs (cont
System Programs (cont’
’d)
d)
„ File modification
z Text editors to create and modify files
z Special commands to search contents of files or perform
transformations of the text
„ Programming-language support - Compilers, assemblers,
debuggers and interpreters sometimes provided
„ Program loading and execution- Absolute loaders, relocatable
loaders, linkage editors, and overlay-loaders, debugging systems
for higher-level and machine language
„ Communications - Provide the mechanism for creating virtual
connections among processes, users, and computer systems
z Allow users to send messages to one another’s screens,
browse web pages, send electronic-mail messages, log in
remotely, transfer files from one machine to another
2.24 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Operating System Design and Implementation
Operating System Design and Implementation
„ Design and Implementation of OS not “solvable”, but some
approaches have proven successful
„ Internal structure of different Operating Systems can vary widely
„ Start by defining goals and specifications
„ Affected by choice of hardware, type of system
„ User goals and System goals
z User goals – operating system should be convenient to use,
easy to learn, reliable, safe, and fast
z System goals – operating system should be easy to design,
implement, and maintain, as well as flexible, reliable, error-free,
and efficient
2.25 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Operating System Design and Implementation (Cont.)
Operating System Design and Implementation (Cont.)
„ Important principle to separate
Policy: What will be done?
Mechanism: How to do it?
„ Mechanisms determine how to do something, policies decide what
will be done
z The separation of policy from mechanism is a very important
principle, it allows maximum flexibility if policy decisions are to
be changed later
2.26 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Simple Structure
Simple Structure
„ MS-DOS – written to provide the most functionality in the least
space
z Not divided into modules
z Although MS-DOS has some structure, its interfaces and levels
of functionality are not well separated
2.27 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
MS
MS-
-DOS Layer Structure
DOS Layer Structure
2.28 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Layered Approach
Layered Approach
„ The operating system is divided into a number of layers (levels),
each built on top of lower layers. The bottom layer (layer 0), is the
hardware; the highest (layer N) is the user interface.
„ With modularity, layers are selected such that each uses functions
(operations) and services of only lower-level layers
2.29 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Layered Operating System
Layered Operating System
2.30 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
UNIX
UNIX
„ UNIX – limited by hardware functionality, the original UNIX operating
system had limited structuring. The UNIX OS consists of two
separable parts
z Systems programs
z The kernel
 Consists of everything below the system-call interface and
above the physical hardware
 Provides the file system, CPU scheduling, memory
management, and other operating-system functions; a large
number of functions for one level
2.31 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
UNIX System Structure
UNIX System Structure
2.32 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Microkernel System Structure
Microkernel System Structure
„ Moves as much from the kernel into “user” space
„ Communication takes place between user modules using message
passing
„ Benefits:
z Easier to extend a microkernel
z Easier to port the operating system to new architectures
z More reliable (less code is running in kernel mode)
z More secure
„ Detriments:
z Performance overhead of user space to kernel space
communication
2.33 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Mac OS X Structure
Mac OS X Structure
2.34 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Modules
Modules
„ Most modern operating systems implement kernel modules
z Uses object-oriented approach
z Each core component is separate
z Each talks to the others over known interfaces
z Each is loadable as needed within the kernel
„ Overall, similar to layers but with more flexible
2.35 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Solaris Modular Approach
Solaris Modular Approach
2.36 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Virtual Machines
Virtual Machines
„ A virtual machine takes the layered approach to its logical
conclusion. It treats hardware and the operating system
kernel as though they were all hardware
„ A virtual machine provides an interface identical to the
underlying bare hardware
„ The operating system creates the illusion of multiple
processes, each executing on its own processor with its own
(virtual) memory
2.37 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Virtual Machines (Cont.)
Virtual Machines (Cont.)
„ The resources of the physical computer are shared to create the
virtual machines
z CPU scheduling can create the appearance that users have
their own processor
z Spooling and a file system can provide virtual card readers and
virtual line printers
z A normal user time-sharing terminal serves as the virtual
machine operator’s console
2.38 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Virtual Machines (Cont.)
Virtual Machines (Cont.)
(a) Nonvirtual machine (b) virtual machine
Non-virtual Machine Virtual Machine
2.39 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Virtual Machines
Virtual Machines (Cont.)
(Cont.)
„ The virtual-machine concept provides complete protection of system
resources since each virtual machine is isolated from all other virtual
machines. This isolation, however, permits no direct sharing of
resources.
„ A virtual-machine system is a perfect vehicle for operating-systems
research and development. System development is done on the
virtual machine, instead of on a physical machine and so does not
disrupt normal system operation.
„ The virtual machine concept is difficult to implement due to the effort
required to provide an exact duplicate to the underlying machine
2.40 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
VMware
VMware Architecture
Architecture
2.41 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
The Java Virtual Machine
The Java Virtual Machine
2.42 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
Operating System Generation
Operating System Generation
„ Operating systems are designed to run on any of a class of
machines; the system must be configured for each specific
computer site
„ SYSGEN program obtains information concerning the specific
configuration of the hardware system
„ Booting – starting a computer by loading the kernel
„ Bootstrap program – code stored in ROM that is able to locate the
kernel, load it into memory, and start its execution
2.43 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Jan 14, 2005
System Boot
System Boot
„ Operating system must be made available to hardware so
hardware can start it
z Small piece of code – bootstrap loader, locates the kernel,
loads it into memory, and starts it
z Sometimes two-step process where boot block at fixed
location loads bootstrap loader
z When power initialized on system, execution starts at a fixed
memory location
 Firmware used to hold initial boot code
End of Chapter 2
End of Chapter 2
Chapter 3: Processes
Chapter 3: Processes
3.2 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Chapter 3: Processes
Chapter 3: Processes
„ Process Concept
„ Process Scheduling
„ Operations on Processes
„ Cooperating Processes
„ Interprocess Communication
„ Communication in Client-Server Systems
3.3 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Process Concept
Process Concept
„ An operating system executes a variety of programs:
z Batch system – jobs
z Time-shared systems – user programs or tasks
„ Textbook uses the terms job and process almost
interchangeably
„ Process – a program in execution; process execution must
progress in sequential fashion
„ A process includes:
z program counter
z stack
z data section
3.4 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Process in Memory
Process in Memory
3.5 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Process State
Process State
„ As a process executes, it changes state
z new: The process is being created
z running: Instructions are being executed
z waiting: The process is waiting for some event to occur
z ready: The process is waiting to be assigned to a processor
z terminated: The process has finished execution
3.6 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Diagram of Process State
Diagram of Process State
3.7 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Process Control Block (PCB)
Process Control Block (PCB)
Information associated with each process
„ Process state
„ Program counter
„ CPU registers
„ CPU scheduling information
„ Memory-management information
„ Accounting information
„ I/O status information
3.8 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Process Control Block (PCB)
Process Control Block (PCB)
3.9 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
CPU Switch From Process to Process
CPU Switch From Process to Process
3.10 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Process Scheduling Queues
Process Scheduling Queues
„ Job queue – set of all processes in the system
„ Ready queue – set of all processes residing in main memory,
ready and waiting to execute
„ Device queues – set of processes waiting for an I/O device
„ Processes migrate among the various queues
3.11 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Ready Queue And Various I/O Device Queues
Ready Queue And Various I/O Device Queues
3.12 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Representation of Process Scheduling
Representation of Process Scheduling
3.13 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Schedulers
Schedulers
„ Long-term scheduler (or job scheduler) – selects which
processes should be brought into the ready queue
„ Short-term scheduler (or CPU scheduler) – selects
which process should be executed next and allocates
CPU
3.14 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Addition of Medium Term Scheduling
Addition of Medium Term Scheduling
3.15 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Schedulers (Cont.)
Schedulers (Cont.)
„ Short-term scheduler is invoked very frequently (milliseconds) ⇒
(must be fast)
„ Long-term scheduler is invoked very infrequently (seconds,
minutes) ⇒ (may be slow)
„ The long-term scheduler controls the degree of multiprogramming
„ Processes can be described as either:
z I/O-bound process – spends more time doing I/O than
computations, many short CPU bursts
z CPU-bound process – spends more time doing computations;
few very long CPU bursts
3.16 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Context Switch
Context Switch
„ When CPU switches to another process, the system must save the
state of the old process and load the saved state for the new
process
„ Context-switch time is overhead; the system does no useful work
while switching
„ Time dependent on hardware support
3.17 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Process Creation
Process Creation
„ Parent process create children processes, which, in turn create
other processes, forming a tree of processes
„ Resource sharing
z Parent and children share all resources
z Children share subset of parent’s resources
z Parent and child share no resources
„ Execution
z Parent and children execute concurrently
z Parent waits until children terminate
3.18 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Process Creation (Cont.)
Process Creation (Cont.)
„ Address space
z Child duplicate of parent
z Child has a program loaded into it
„ UNIX examples
z fork system call creates new process
z exec system call used after a fork to replace the process’
memory space with a new program
3.19 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Process Creation
Process Creation
3.20 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
C Program Forking Separate Process
C Program Forking Separate Process
int main()
{
pid_t pid;
/* fork another process */
pid = fork();
if (pid  0) { /* error occurred */
fprintf(stderr, Fork Failed);
exit(-1);
}
else if (pid == 0) { /* child process */
execlp(/bin/ls, ls, NULL);
}
else { /* parent process */
/* parent will wait for the child to complete */
wait (NULL);
printf (Child Complete);
exit(0);
}
}
3.21 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
A tree of processes on a typical Solaris
A tree of processes on a typical Solaris
3.22 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Process Termination
Process Termination
„ Process executes last statement and asks the operating system to
delete it (exit)
z Output data from child to parent (via wait)
z Process’ resources are deallocated by operating system
„ Parent may terminate execution of children processes (abort)
z Child has exceeded allocated resources
z Task assigned to child is no longer required
z If parent is exiting
 Some operating system do not allow child to continue if its
parent terminates
– All children terminated - cascading termination
3.23 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Cooperating Processes
Cooperating Processes
„ Independent process cannot affect or be affected by the execution
of another process
„ Cooperating process can affect or be affected by the execution of
another process
„ Advantages of process cooperation
z Information sharing
z Computation speed-up
z Modularity
z Convenience
3.24 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Producer
Producer-
-Consumer Problem
Consumer Problem
„ Paradigm for cooperating processes, producer process
produces information that is consumed by a consumer
process
z unbounded-buffer places no practical limit on the size of
the buffer
z bounded-buffer assumes that there is a fixed buffer size
3.25 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Bounded
Bounded-
-Buffer
Buffer –
– Shared
Shared-
-Memory Solution
Memory Solution
„ Shared data
#define BUFFER_SIZE 10
typedef struct {
. . .
} item;
item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
„ Solution is correct, but can only use BUFFER_SIZE-1 elements
3.26 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Bounded
Bounded-
-Buffer
Buffer –
– Insert() Method
Insert() Method
while (true) {
/* Produce an item */
while (((in = (in + 1) % BUFFER SIZE count) == out)
; /* do nothing -- no free buffers */
buffer[in] = item;
in = (in + 1) % BUFFER SIZE;
}
3.27 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Bounded Buffer
Bounded Buffer –
– Remove() Method
Remove() Method
while (true) {
while (in == out)
; // do nothing -- nothing to consume
// remove an item from the buffer
item = buffer[out];
out = (out + 1) % BUFFER SIZE;
return item;
}
3.28 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Interprocess
Interprocess Communication (IPC)
Communication (IPC)
„ Mechanism for processes to communicate and to synchronize their
actions
„ Message system – processes communicate with each other without
resorting to shared variables
„ IPC facility provides two operations:
z send(message) – message size fixed or variable
z receive(message)
„ If P and Q wish to communicate, they need to:
z establish a communication link between them
z exchange messages via send/receive
„ Implementation of communication link
z physical (e.g., shared memory, hardware bus)
z logical (e.g., logical properties)
3.29 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Implementation Questions
Implementation Questions
„ How are links established?
„ Can a link be associated with more than two processes?
„ How many links can there be between every pair of communicating
processes?
„ What is the capacity of a link?
„ Is the size of a message that the link can accommodate fixed or
variable?
„ Is a link unidirectional or bi-directional?
3.30 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Communications Models
Communications Models
3.31 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Direct Communication
Direct Communication
„ Processes must name each other explicitly:
z send (P, message) – send a message to process P
z receive(Q, message) – receive a message from process Q
„ Properties of communication link
z Links are established automatically
z A link is associated with exactly one pair of communicating
processes
z Between each pair there exists exactly one link
z The link may be unidirectional, but is usually bi-directional
3.32 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Indirect Communication
Indirect Communication
„ Messages are directed and received from mailboxes (also
referred to as ports)
z Each mailbox has a unique id
z Processes can communicate only if they share a mailbox
„ Properties of communication link
z Link established only if processes share a common mailbox
z A link may be associated with many processes
z Each pair of processes may share several communication
links
z Link may be unidirectional or bi-directional
3.33 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Indirect Communication
Indirect Communication
„ Operations
z create a new mailbox
z send and receive messages through mailbox
z destroy a mailbox
„ Primitives are defined as:
send(A, message) – send a message to mailbox A
receive(A, message) – receive a message from mailbox A
3.34 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Indirect Communication
Indirect Communication
„ Mailbox sharing
z P1, P2, and P3 share mailbox A
z P1, sends; P2 and P3 receive
z Who gets the message?
„ Solutions
z Allow a link to be associated with at most two processes
z Allow only one process at a time to execute a receive operation
z Allow the system to select arbitrarily the receiver. Sender is
notified who the receiver was.
3.35 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Synchronization
Synchronization
„ Message passing may be either blocking or non-blocking
„ Blocking is considered synchronous
z Blocking send has the sender block until the message is
received
z Blocking receive has the receiver block until a message is
available
„ Non-blocking is considered asynchronous
z Non-blocking send has the sender send the message and
continue
z Non-blocking receive has the receiver receive a valid
message or null
3.36 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Buffering
Buffering
„ Queue of messages attached to the link; implemented in one of
three ways
1. Zero capacity – 0 messages
Sender must wait for receiver (rendezvous)
2. Bounded capacity – finite length of n messages
Sender must wait if link full
3. Unbounded capacity – infinite length
Sender never waits
3.37 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Client
Client-
-Server Communication
Server Communication
„ Sockets
„ Remote Procedure Calls
„ Remote Method Invocation (Java)
3.38 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Sockets
Sockets
„ A socket is defined as an endpoint for communication
„ Concatenation of IP address and port
„ The socket 161.25.19.8:1625 refers to port 1625 on host
161.25.19.8
„ Communication consists between a pair of sockets
3.39 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Socket Communication
Socket Communication
3.40 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Remote Procedure Calls
Remote Procedure Calls
„ Remote procedure call (RPC) abstracts procedure calls between
processes on networked systems.
„ Stubs – client-side proxy for the actual procedure on the server.
„ The client-side stub locates the server and marshalls the
parameters.
„ The server-side stub receives this message, unpacks the
marshalled parameters, and peforms the procedure on the server.
3.41 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Execution of RPC
Execution of RPC
3.42 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Remote Method Invocation
Remote Method Invocation
„ Remote Method Invocation (RMI) is a Java mechanism similar to
RPCs.
„ RMI allows a Java program on one machine to invoke a method on
a remote object.
3.43 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts - 7th Edition, Feb 7, 2006
Marshalling Parameters
Marshalling Parameters
End of Chapter 3
End of Chapter 3
Chapter 4: Threads
Chapter 4: Threads
4.2 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Chapter 4: Threads
Chapter 4: Threads
„ Overview
„ Multithreading Models
„ Threading Issues
„ Pthreads
„ Windows XP Threads
„ Linux Threads
„ Java Threads
4.3 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Single and Multithreaded Processes
Single and Multithreaded Processes
4.4 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Benefits
Benefits
„ Responsiveness
„ Resource Sharing
„ Economy
„ Utilization of MP Architectures
4.5 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
User Threads
User Threads
„ Thread management done by user-level threads library
„ Three primary thread libraries:
z POSIX Pthreads
z Win32 threads
z Java threads
4.6 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Kernel Threads
Kernel Threads
„ Supported by the Kernel
„ Examples
z Windows XP/2000
z Solaris
z Linux
z Tru64 UNIX
z Mac OS X
4.7 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Multithreading Models
Multithreading Models
„ Many-to-One
„ One-to-One
„ Many-to-Many
4.8 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Many
Many-
-to
to-
-One
One
„ Many user-level threads mapped to single kernel thread
„ Examples:
z Solaris Green Threads
z GNU Portable Threads
4.9 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Many
Many-
-to
to-
-One Model
One Model
4.10 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
One
One-
-to
to-
-One
One
„ Each user-level thread maps to kernel thread
„ Examples
z Windows NT/XP/2000
z Linux
z Solaris 9 and later
4.11 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
One
One-
-to
to-
-one Model
one Model
4.12 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Many
Many-
-to
to-
-Many Model
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
4.13 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Many
Many-
-to
to-
-Many Model
Many Model
4.14 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Two
Two-
-level Model
level Model
„ Similar to M:M, except that it allows a user thread to be
bound to kernel thread
„ Examples
z IRIX
z HP-UX
z Tru64 UNIX
z Solaris 8 and earlier
4.15 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Two
Two-
-level Model
level Model
4.16 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Threading Issues
Threading Issues
„ Semantics of fork() and exec() system calls
„ Thread cancellation
„ Signal handling
„ Thread pools
„ Thread specific data
„ Scheduler activations
4.17 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Semantics of fork() and exec()
Semantics of fork() and exec()
„ Does fork() duplicate only the calling thread or all threads?
4.18 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Thread Cancellation
Thread Cancellation
„ Terminating a thread before it has finished
„ Two general approaches:
z Asynchronous cancellation terminates the target
thread immediately
z Deferred cancellation allows the target thread to
periodically check if it should be cancelled
4.19 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Signal Handling
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
„ Options:
z Deliver the signal to the thread to which the signal applies
z Deliver the signal to every thread in the process
z Deliver the signal to certain threads in the process
z Assign a specific threa to receive all signals for the process
4.20 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Thread Pools
Thread Pools
„ Create a number of threads in a pool where they await work
„ Advantages:
z Usually slightly faster to service a request with an existing
thread than create a new thread
z Allows the number of threads in the application(s) to be
bound to the size of the pool
4.21 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Thread Specific Data
Thread Specific Data
„ 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)
4.22 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Scheduler Activations
Scheduler Activations
„ Both M:M and Two-level models require communication to
maintain the appropriate number of kernel threads allocated
to the application
„ Scheduler activations provide upcalls - a communication
mechanism from the kernel to the thread library
„ This communication allows an application to maintain the
correct number kernel threads
4.23 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Pthreads
Pthreads
„ A POSIX standard (IEEE 1003.1c) API for thread
creation and synchronization
„ 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)
4.24 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Windows XP Threads
Windows XP Threads
„ Implements the one-to-one mapping
„ Each thread contains
z A thread id
z Register set
z Separate user and kernel stacks
z Private data storage area
„ The register set, stacks, and private storage area are known
as the context of the threads
„ The primary data structures of a thread include:
z ETHREAD (executive thread block)
z KTHREAD (kernel thread block)
z TEB (thread environment block)
4.25 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Linux Threads
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)
4.26 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Java Threads
Java Threads
„ Java threads are managed by the JVM
„ Java threads may be created by:
z Extending Thread class
z Implementing the Runnable interface
4.27 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th edition, Jan 23, 2005
Java Thread States
Java Thread States
End of Chapter 4
End of Chapter 4
Chapter 5: CPU Scheduling
Chapter 5: CPU Scheduling
5.2 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Chapter 5: CPU Scheduling
Chapter 5: CPU Scheduling
„ Basic Concepts
„ Scheduling Criteria
„ Scheduling Algorithms
„ Multiple-Processor Scheduling
„ Real-Time Scheduling
„ Thread Scheduling
„ Operating Systems Examples
„ Java Thread Scheduling
„ Algorithm Evaluation
5.3 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Basic Concepts
Basic Concepts
„ Maximum CPU utilization obtained with multiprogramming
„ CPU–I/O Burst Cycle – Process execution consists of a cycle of
CPU execution and I/O wait
„ CPU burst distribution
5.4 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Alternating Sequence of CPU And I/O Bursts
Alternating Sequence of CPU And I/O Bursts
5.5 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Histogram of CPU
Histogram of CPU-
-burst Times
burst Times
5.6 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
CPU Scheduler
CPU Scheduler
„ Selects from among the processes in memory that are ready to
execute, and allocates the CPU to one of them
„ CPU scheduling decisions may take place when a process:
1. Switches from running to waiting state
2. Switches from running to ready state
3. Switches from waiting to ready
4. Terminates
„ Scheduling under 1 and 4 is nonpreemptive
„ All other scheduling is preemptive
5.7 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Dispatcher
Dispatcher
„ Dispatcher module gives control of the CPU to the process
selected by the short-term scheduler; this involves:
z switching context
z switching to user mode
z jumping to the proper location in the user program to restart
that program
„ Dispatch latency – time it takes for the dispatcher to stop one
process and start another running
5.8 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Scheduling Criteria
Scheduling Criteria
„ CPU utilization – keep the CPU as busy as possible
„ Throughput – # of processes that complete their execution
per time unit
„ Turnaround time – amount of time to execute a particular
process
„ Waiting time – amount of time a process has been waiting
in the ready queue
„ Response time – amount of time it takes from when a
request was submitted until the first response is produced,
not output (for time-sharing environment)
5.9 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Optimization Criteria
Optimization Criteria
„ Max CPU utilization
„ Max throughput
„ Min turnaround time
„ Min waiting time
„ Min response time
5.10 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
First
First-
-Come, First
Come, First-
-Served (FCFS) Scheduling
Served (FCFS) Scheduling
Process Burst Time
P1 24
P2 3
P3 3
„ Suppose that the processes arrive in the order: P1 , P2 , P3
The Gantt Chart for the schedule is:
„ Waiting time for P1 = 0; P2 = 24; P3 = 27
„ Average waiting time: (0 + 24 + 27)/3 = 17
P1 P2 P3
24 27 30
0
5.11 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
FCFS Scheduling (Cont.)
FCFS Scheduling (Cont.)
Suppose that the processes arrive in the order
P2 , P3 , P1
„ The Gantt chart for the schedule is:
„ Waiting time for P1 = 6; P2 = 0; P3 = 3
„ Average waiting time: (6 + 0 + 3)/3 = 3
„ Much better than previous case
„ Convoy effect short process behind long process
P1
P3
P2
6
3 30
0
5.12 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Shortest
Shortest-
-Job
Job-
-First (SJF) Scheduling
First (SJF) Scheduling
„ Associate with each process the length of its next CPU burst. Use
these lengths to schedule the process with the shortest time
„ Two schemes:
z nonpreemptive – once CPU given to the process it cannot be
preempted until completes its CPU burst
z preemptive – if a new process arrives with CPU burst length
less than remaining time of current executing process,
preempt. This scheme is know as the
Shortest-Remaining-Time-First (SRTF)
„ SJF is optimal – gives minimum average waiting time for a given
set of processes
5.13 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Process Arrival Time Burst Time
P1 0.0 7
P2 2.0 4
P3 4.0 1
P4 5.0 4
„ SJF (non-preemptive)
„ Average waiting time = (0 + 6 + 3 + 7)/4 = 4
Example of Non
Example of Non-
-Preemptive SJF
Preemptive SJF
P1 P3 P2
7
3 16
0
P4
8 12
5.14 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Example of Preemptive SJF
Example of Preemptive SJF
Process Arrival Time Burst Time
P1 0.0 7
P2 2.0 4
P3 4.0 1
P4 5.0 4
„ SJF (preemptive)
„ Average waiting time = (9 + 1 + 0 +2)/4 = 3
P1 P3
P2
4
2 11
0
P4
5 7
P2 P1
16
5.15 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Determining Length of Next CPU Burst
Determining Length of Next CPU Burst
„ Can only estimate the length
„ Can be done by using the length of previous CPU bursts, using
exponential averaging
:
Define
4.
1
0
,
3.
burst
CPU
next
the
for
value
predicted
2.
burst
CPU
of
length
actual
1.
≤
≤
=
=
+
α
α
τ 1
n
th
n n
t
( ) .
1
1 n
n
n t τ
α
α
τ −
+
=
=
5.16 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Prediction of the Length of the Next CPU Burst
Prediction of the Length of the Next CPU Burst
5.17 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Examples of Exponential Averaging
Examples of Exponential Averaging
„ α =0
z τn+1 = τn
z Recent history does not count
„ α =1
z τn+1 = α tn
z Only the actual last CPU burst counts
„ If we expand the formula, we get:
τn+1 = α tn+(1 - α)α tn -1 + …
+(1 - α )j α tn -j + …
+(1 - α )n +1 τ0
„ Since both α and (1 - α) are less than or equal to 1, each
successive term has less weight than its predecessor
5.18 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Priority Scheduling
Priority Scheduling
„ A priority number (integer) is associated with each process
„ The CPU is allocated to the process with the highest priority
(smallest integer ≡ highest priority)
z Preemptive
z nonpreemptive
„ SJF is a priority scheduling where priority is the predicted next CPU
burst time
„ Problem ≡ Starvation – low priority processes may never execute
„ Solution ≡ Aging – as time progresses increase the priority of the
process
5.19 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Round Robin (RR)
Round Robin (RR)
„ Each process gets a small unit of CPU time (time quantum),
usually 10-100 milliseconds. After this time has elapsed, the
process is preempted and added to the end of the ready queue.
„ If there are n processes in the ready queue and the time
quantum is q, then each process gets 1/n of the CPU time in
chunks of at most q time units at once. No process waits more
than (n-1)q time units.
„ Performance
z q large ⇒ FIFO
z q small ⇒ q must be large with respect to context switch,
otherwise overhead is too high
5.20 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Example of RR with Time Quantum = 20
Example of RR with Time Quantum = 20
Process Burst Time
P1 53
P2 17
P3 68
P4 24
„ The Gantt chart is:
„ Typically, higher average turnaround than SJF, but better response
P1 P2 P3 P4 P1 P3 P4 P1 P3 P3
0 20 37 57 77 97 117 121 134 154 162
5.21 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Time Quantum and Context Switch Time
Time Quantum and Context Switch Time
5.22 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Turnaround Time Varies With The Time Quantum
Turnaround Time Varies With The Time Quantum
5.23 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Multilevel Queue
Multilevel Queue
„ Ready queue is partitioned into separate queues:
foreground (interactive)
background (batch)
„ Each queue has its own scheduling algorithm
z foreground – RR
z background – FCFS
„ Scheduling must be done between the queues
z Fixed priority scheduling; (i.e., serve all from foreground then
from background). Possibility of starvation.
z Time slice – each queue gets a certain amount of CPU time
which it can schedule amongst its processes; i.e., 80% to
foreground in RR
z 20% to background in FCFS
5.24 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Multilevel Queue Scheduling
Multilevel Queue Scheduling
5.25 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Multilevel Feedback Queue
Multilevel Feedback Queue
„ A process can move between the various queues; aging can be
implemented this way
„ Multilevel-feedback-queue scheduler defined by the following
parameters:
z number of queues
z scheduling algorithms for each queue
z method used to determine when to upgrade a process
z method used to determine when to demote a process
z method used to determine which queue a process will enter
when that process needs service
5.26 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Example of Multilevel Feedback Queue
Example of Multilevel Feedback Queue
„ Three queues:
z Q0 – RR with time quantum 8 milliseconds
z Q1 – RR time quantum 16 milliseconds
z Q2 – FCFS
„ Scheduling
z A new job enters queue Q0 which is served FCFS. When it
gains CPU, job receives 8 milliseconds. If it does not finish in 8
milliseconds, job is moved to queue Q1.
z At Q1 job is again served FCFS and receives 16 additional
milliseconds. If it still does not complete, it is preempted and
moved to queue Q2.
5.27 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Multilevel Feedback Queues
Multilevel Feedback Queues
5.28 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Multiple
Multiple-
-Processor Scheduling
Processor Scheduling
„ CPU scheduling more complex when multiple CPUs are
available
„ Homogeneous processors within a multiprocessor
„ Load sharing
„ Asymmetric multiprocessing – only one processor
accesses the system data structures, alleviating the need
for data sharing
Processor Affinity: sched_setaffinity()
Multicore processors
5.29 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Real
Real-
-Time Scheduling
Time Scheduling
„ Hard real-time systems – required to complete a
critical task within a guaranteed amount of time
„ Soft real-time computing – requires that critical
processes receive priority over less fortunate ones
Dispatch Latency
Interrupt Latency
5.30 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Thread Scheduling
Thread Scheduling
„ Local Scheduling – How the threads library decides which
thread to put onto an available LWP
„ Global Scheduling – How the kernel decides which kernel
thread to run next
Process Contention Scope
System Contention Scope
5.31 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Pthread
Pthread Scheduling API
Scheduling API
#include pthread.h
#include stdio.h
#define NUM THREADS 5
int main(int argc, char *argv[])
{
int i;
pthread t tid[NUM THREADS];
pthread attr t attr;
/* get the default attributes */
pthread attr init(attr);
/* set the scheduling algorithm to PROCESS or SYSTEM */
pthread attr setscope(attr, PTHREAD SCOPE SYSTEM);
/* set the scheduling policy - FIFO, RT, or OTHER */
pthread attr setschedpolicy(attr, SCHED OTHER);
/* create the threads */
for (i = 0; i  NUM THREADS; i++)
pthread create(tid[i],attr,runner,NULL);
5.32 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Pthread
Pthread Scheduling API
Scheduling API
/* now join on each thread */
for (i = 0; i  NUM THREADS; i++)
pthread join(tid[i], NULL);
}
/* Each thread will begin control in this function */
void *runner(void *param)
{
printf(I am a threadn);
pthread exit(0);
}
5.33 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Operating System Examples
Operating System Examples
„ Solaris scheduling
„ Windows XP scheduling
„ Linux scheduling
5.34 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Solaris 2 Scheduling
Solaris 2 Scheduling
5.35 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Solaris Dispatch Table
Solaris Dispatch Table
5.36 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Windows XP Priorities
Windows XP Priorities
5.37 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Linux Scheduling
Linux Scheduling
„ Two algorithms: time-sharing and real-time
„ Time-sharing
z Prioritized credit-based – process with most credits is
scheduled next
z Credit subtracted when timer interrupt occurs
z When credit = 0, another process chosen
z When all processes have credit = 0, recrediting occurs
 Based on factors including priority and history
„ Real-time
z Soft real-time
z Posix.1b compliant – two classes
 FCFS and RR
 Highest priority process always runs first
5.38 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
The Relationship Between Priorities and Time
The Relationship Between Priorities and Time-
-slice length
slice length
5.39 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
List of Tasks Indexed According to
List of Tasks Indexed According to Prorities
Prorities
5.40 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Algorithm Evaluation
Algorithm Evaluation
„ Deterministic modeling – takes a particular
predetermined workload and defines the performance of
each algorithm for that workload
„ Queueing models
„ Implementation
5.41 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
5.15
5.15
End of Chapter 5
End of Chapter 5
5.43 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
5.08
5.08
5.44 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
In
In-
-5.7
5.7
5.45 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
In
In-
-5.8
5.8
5.46 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
In
In-
-5.9
5.9
5.47 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Dispatch Latency
Dispatch Latency
5.48 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Java Thread Scheduling
Java Thread Scheduling
„ JVM Uses a Preemptive, Priority-Based Scheduling Algorithm
„ FIFO Queue is Used if There Are Multiple Threads With the Same
Priority
5.49 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Java Thread Scheduling (cont)
Java Thread Scheduling (cont)
JVM Schedules a Thread to Run When:
1. The Currently Running Thread Exits the Runnable State
2. A Higher Priority Thread Enters the Runnable State
* Note – the JVM Does Not Specify Whether Threads are Time-Sliced
or Not
5.50 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Time
Time-
-Slicing
Slicing
Since the JVM Doesn’t Ensure Time-Slicing, the yield() Method
May Be Used:
while (true) {
// perform CPU-intensive task
. . .
Thread.yield();
}
This Yields Control to Another Thread of Equal Priority
5.51 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 2, 2005
Thread Priorities
Thread Priorities
Priority Comment
Thread.MIN_PRIORITY Minimum Thread Priority
Thread.MAX_PRIORITY Maximum Thread Priority
Thread.NORM_PRIORITY Default Thread Priority
Priorities May Be Set Using setPriority() method:
setPriority(Thread.NORM_PRIORITY + 2);
Chapter 6: Process Synchronization
Chapter 6: Process Synchronization
6.2 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Module 6: Process Synchronization
Module 6: Process Synchronization
„ Background
„ The Critical-Section Problem
„ Peterson’s Solution
„ Synchronization Hardware
„ Semaphores
„ Classic Problems of Synchronization
„ Monitors
„ Synchronization Examples
„ Atomic Transactions
cooperating Competing
Process
6.3 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Background
Background
„ Concurrent access to shared data may result in data
inconsistency
„ Maintaining data consistency requires mechanisms to
ensure the orderly execution of cooperating processes
„ Suppose that we wanted to provide a solution to the
consumer-producer problem that fills all the buffers. We
can do so by having an integer count that keeps track of
the number of full buffers. Initially, count is set to 0. It is
incremented by the producer after it produces a new
buffer and is decremented by the consumer after it
consumes a buffer.
6.4 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Producer
Producer
while (true) {
/* produce an item and put in nextProduced */
while (count == BUFFER_SIZE)
; // do nothing
buffer [in] = nextProduced;
in = (in + 1) % BUFFER_SIZE;
count++;
}
Buffer
Count=0
{N}
0
1
2
N-1
6.5 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Consumer
Consumer
while (true) {
while (count == 0)
; // do nothing
nextConsumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count--;
/* consume the item in nextConsumed
}
Count=5
6.6 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Race Condition
Race Condition
„ count++ could be implemented as
register1 = count
register1 = register1 + 1
count = register1
„ count-- could be implemented as
register2 = count
register2 = register2 - 1
count = register2
„ Consider this execution interleaving with “count = 5” initially:
S0: producer execute register1 = count {register1 = 5}
S1: producer execute register1 = register1 + 1 {register1 = 6}
S2: consumer execute register2 = count {register2 = 5}
S3: consumer execute register2 = register2 - 1 {register2 = 4}
S4: producer execute count = register1 {count = 6 }
S5: consumer execute count = register2 {count = 4}
5
6
6
5
4
4
6.7 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Solution to Critical
Solution to Critical-
-Section Problem
Section Problem
1. Mutual Exclusion - If process Pi is executing in its critical section,
then no other processes can be executing in their critical sections
2. Progress - If no process is executing in its critical section and
there exist some processes that wish to enter their critical section,
then the selection of the processes that will enter the critical
section next cannot be postponed indefinitely
3. Bounded Waiting - A bound must exist on the number of times
that other processes are allowed to enter their critical sections
after a process has made a request to enter its critical section and
before that request is granted
y Assume that each process executes at a nonzero speed
y No assumption concerning relative speed of the N processes
Entry
Section
Critical
Section
Exit
Sec Remainder
Section
P1
P2
P3
6.8 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Peterson
Peterson’
’s Solution
s Solution
„ Two process solution
„ Assume that the LOAD and STORE instructions are atomic;
that is, cannot be interrupted.
„ The two processes share two variables:
z int turn;
z Boolean flag[2]
„ The variable turn indicates whose turn it is to enter the
critical section.
„ The flag array is used to indicate if a process is ready to
enter the critical section. flag[i] = true implies that process Pi
is ready!
6.9 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Algorithm for Process
Algorithm for Process P
Pi
i
while (true) {
flag[i] = TRUE;
turn = j;
while ( flag[j]  turn == j);
CRITICAL SECTION
flag[i] = FALSE;
REMAINDER SECTION
}
while(true) {
flag[j]= TRUE;
turn = i;
while( flag[i]  turn == i ) ;
//waiting
CRITICAL SECTION
flag[j]= FALSE;
REMAINDER SECTION
}
PROCESS Pj
6.10 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Synchronization Hardware
Synchronization Hardware
„ Many systems provide hardware support for critical section
code
„ Uniprocessors – could disable interrupts
z Currently running code would execute without
preemption
z Generally too inefficient on multiprocessor systems
 Operating systems using this not broadly scalable
„ Modern machines provide special atomic hardware
instructions
 Atomic = non-interruptable
z Either test memory word and set value
z Or swap contents of two memory words
6.11 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
TestAndndSet
TestAndndSet Instruction
Instruction
„ Definition:
boolean TestAndSet (boolean *target)
{
boolean rv = *target;
*target = TRUE;
return rv:
}
multiprocess solution
Lock
6.12 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Solution using
Solution using TestAndSet
TestAndSet
„ Shared boolean variable lock., initialized to false.
„ Solution:
while (true) {
while ( TestAndSet (lock ))
; /* do nothing
// critical section
lock = FALSE;
// remainder section
}
6.13 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Swap Instruction
Swap Instruction
„ Definition:
void Swap (boolean *a, boolean *b)
{
boolean temp = *a;
*a = *b;
*b = temp:
}
6.14 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Solution using Swap
Solution using Swap
„ Shared Boolean variable lock initialized to FALSE; Each
process has a local Boolean variable key.
„ Solution:
while (true) {
key = TRUE;
while ( key == TRUE)
Swap (lock, key );
// critical section
lock = FALSE;
// remainder section
}
6.15 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Semaphore
Semaphore
„ Synchronization tool that does not require busy waiting
„ Semaphore S – integer variable
„ Two standard operations modify S: wait() and signal()
z Originally called P() and V()
„ Less complicated
„ Can only be accessed via two indivisible (atomic) operations
z wait (S) {
while S = 0
; // no-op
S--;
}
z signal (S) {
S++;
}
6.16 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Semaphore as General Synchronization Tool
Semaphore as General Synchronization Tool
„ Counting semaphore – integer value can range over an
unrestricted domain
„ Binary semaphore – integer value can range only between 0
and 1; can be simpler to implement
z Also known as mutex locks
„ Can implement a counting semaphore S as a binary semaphore
„ Provides mutual exclusion
z Semaphore S; // initialized to 1
z wait (S);
Critical Section
signal (S);
acquire(){
while( ! available )
; / waiting
available = false;
}
release(){
available = true;
}
do{
acquire lock;
CS
release lock
RSection
}
6.17 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Semaphore Implementation
Semaphore Implementation
„ Must guarantee that no two processes can execute wait () and
signal () on the same semaphore at the same time
„ Thus, implementation becomes the critical section problem
where the wait and signal code are placed in the crtical
section.
z Could now have busy waiting in critical section
implementation
 But implementation code is short
 Little busy waiting if critical section rarely occupied
„ Note that applications may spend lots of time in critical sections
and therefore this is not a good solution.
p1 p2 p3
6.18 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Semaphore Implementation with no Busy waiting
Semaphore Implementation with no Busy waiting
„ With each semaphore there is an associated waiting queue.
Each entry in a waiting queue has two data items:
z value (of type integer)
z pointer to next record in the list
„ Two operations:
z block – place the process invoking the operation on the
appropriate waiting queue.
z wakeup – remove one of processes in the waiting queue
and place it in the ready queue.
6.19 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Semaphore Implementation with no Busy waiting
Semaphore Implementation with no Busy waiting (Cont.)
(Cont.)
„ Implementation of wait:
wait (S){
value--;
if (value  0) {
add this process to waiting queue
block(); }
}
„ Implementation of signal:
Signal (S){
value++;
if (value = 0) {
remove a process P from the waiting queue
wakeup(P); }
}
6.20 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Deadlock and Starvation
Deadlock and Starvation
„ Deadlock – two or more processes are waiting indefinitely for an
event that can be caused by only one of the waiting processes
„ Let S and Q be two semaphores initialized to 1
P0 P1
wait (S); wait (Q);
wait (Q); wait (S);
. .
. .
. .
signal (S); signal (Q);
signal (Q); signal (S);
„ Starvation – indefinite blocking. A process may never be removed
from the semaphore queue in which it is suspended.
Priority Inversion:
L  M  H
6.21 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Classical Problems of Synchronization
Classical Problems of Synchronization
„ Bounded-Buffer Problem
„ Readers and Writers Problem
„ Dining-Philosophers Problem
Priority inversion:
L  M  H ---- R
P3 - H
P1- L
6.22 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Bounded
Bounded-
-Buffer Problem
Buffer Problem
„ N buffers, each can hold one item
„ Semaphore mutex initialized to the value 1
„ Semaphore full initialized to the value 0
„ Semaphore empty initialized to the value N.
Buffer [N]
6.23 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Bounded Buffer Problem (Cont.)
Bounded Buffer Problem (Cont.)
„ The structure of the producer process
while (true) {
// produce an item
wait (empty);
wait (mutex);
// add the item to the buffer
signal (mutex);
signal (full);
}
Buffer[in] = itemp(p)
in = (in +1) mod N
6.24 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Bounded Buffer Problem (Cont.)
Bounded Buffer Problem (Cont.)
„ The structure of the consumer process
while (true) {
wait (full);
wait (mutex);
// remove an item from buffer
signal (mutex);
signal (empty);
// consume the removed item
}
6.25 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Readers
Readers-
-Writers Problem
Writers Problem
„ A data set is shared among a number of concurrent processes
z Readers – only read the data set; they do not perform any
updates
z Writers – can both read and write.
„ Problem – allow multiple readers to read at the same time. Only
one single writer can access the shared data at the same time.
„ Shared Data
z Data set
z Semaphore mutex initialized to 1.
z Semaphore wrt initialized to 1.
z Integer readcount initialized to 0.
6.26 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Readers
Readers-
-Writers Problem (Cont.)
Writers Problem (Cont.)
„ The structure of a writer process
while (true) {
wait (wrt) ;
// writing is performed
signal (wrt) ;
}
6.27 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Readers
Readers-
-Writers Problem (Cont.)
Writers Problem (Cont.)
„ The structure of a reader process
while (true) {
wait (mutex) ;
readcount ++ ;
if (readcount == 1) wait (wrt) ;
signal (mutex)
// reading is performed
wait (mutex) ;
readcount - - ;
if (readcount == 0) signal (wrt) ;
signal (mutex) ;
}
6.28 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Dining
Dining-
-Philosophers Problem
Philosophers Problem
„ Shared data
z Bowl of rice (data set)
z Semaphore chopstick [5] initialized to 1
6.29 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Dining
Dining-
-Philosophers Problem (Cont.)
Philosophers Problem (Cont.)
„ The structure of Philosopher i:
While (true) {
wait ( chopstick[i] );
wait ( chopStick[ (i + 1) % 5] );
// eat
signal ( chopstick[i] );
signal (chopstick[ (i + 1) % 5] );
// think
}
6.30 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Problems with Semaphores
Problems with Semaphores
„ Incorrect use of semaphore operations:
z signal (mutex) …. wait (mutex)
z wait (mutex) … wait (mutex)
z Omitting of wait (mutex) or signal (mutex) (or both)
6.31 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Monitors
Monitors
„ A high-level abstraction that provides a convenient and effective
mechanism for process synchronization
„ Only one process may be active within the monitor at a time
monitor monitor-name
{
// shared variable declarations
procedure P1 (…) { …. }
…
procedure Pn (…) {……}
Initialization code ( ….) { … }
…
}
}
6.32 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Schematic view of a Monitor
Schematic view of a Monitor
6.33 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Condition Variables
Condition Variables
„ condition x, y;
„ Two operations on a condition variable:
z x.wait () – a process that invokes the operation is
suspended.
z x.signal () – resumes one of processes (if any) that
invoked x.wait ()
6.34 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Monitor with Condition Variables
Monitor with Condition Variables
6.35 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Solution to Dining Philosophers
Solution to Dining Philosophers
monitor DP
{
enum { THINKING; HUNGRY, EATING) state [5] ;
condition self [5];
void pickup (int i) {
state[i] = HUNGRY;
test(i);
if (state[i] != EATING) self [i].wait;
}
void putdown (int i) {
state[i] = THINKING;
// test left and right neighbors
test((i + 4) % 5);
test((i + 1) % 5);
}
6.36 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Solution to Dining Philosophers (cont)
Solution to Dining Philosophers (cont)
void test (int i) {
if ( (state[(i + 4) % 5] != EATING) 
(state[i] == HUNGRY) 
(state[(i + 1) % 5] != EATING) ) {
state[i] = EATING ;
self[i].signal () ;
}
}
initialization_code() {
for (int i = 0; i  5; i++)
state[i] = THINKING;
}
}
6.37 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Solution to Dining Philosophers (cont)
Solution to Dining Philosophers (cont)
„ Each philosopher I invokes the operations pickup()
and putdown() in the following sequence:
dp.pickup (i)
EAT
dp.putdown (i)
6.38 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Monitor Implementation Using Semaphores
Monitor Implementation Using Semaphores
„ Variables
semaphore mutex; // (initially = 1)
semaphore next; // (initially = 0)
int next-count = 0;
„ Each procedure F will be replaced by
wait(mutex);
…
body of F;
…
if (next-count  0)
signal(next)
else
signal(mutex);
„ Mutual exclusion within a monitor is ensured.
6.39 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Monitor Implementation
Monitor Implementation
„ For each condition variable x, we have:
semaphore x-sem; // (initially = 0)
int x-count = 0;
„ The operation x.wait can be implemented as:
x-count++;
if (next-count  0)
signal(next);
else
signal(mutex);
wait(x-sem);
x-count--;
6.40 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Monitor Implementation
Monitor Implementation
„ The operation x.signal can be implemented as:
if (x-count  0) {
next-count++;
signal(x-sem);
wait(next);
next-count--;
}
6.41 Silberschatz, Galvin and Gagne ©2005
Operating System Concepts – 7th Edition, Feb 8, 2005
Synchronization Examples
Synchronization Examples
„ Solaris
„ Windows XP
„ Linux
„ Pthreads
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf
chp1_merged.pdf

More Related Content

Similar to chp1_merged.pdf

ch1.ppt
ch1.pptch1.ppt
Linux operating system fundamentals of Operating System
Linux operating system fundamentals of Operating SystemLinux operating system fundamentals of Operating System
Linux operating system fundamentals of Operating System
IraqReshi
 

Similar to chp1_merged.pdf (20)

Ch1
Ch1Ch1
Ch1
 
Ch1-Operating System Concept
Ch1-Operating System ConceptCh1-Operating System Concept
Ch1-Operating System Concept
 
Ch1-Operating System Concepts
Ch1-Operating System ConceptsCh1-Operating System Concepts
Ch1-Operating System Concepts
 
Introduction_to_OperatingSystems_ch1.ppt
Introduction_to_OperatingSystems_ch1.pptIntroduction_to_OperatingSystems_ch1.ppt
Introduction_to_OperatingSystems_ch1.ppt
 
ch1.ppt
ch1.pptch1.ppt
ch1.ppt
 
ch1.ppt
ch1.pptch1.ppt
ch1.ppt
 
ch1.ppt
ch1.pptch1.ppt
ch1.ppt
 
ch1.ppt
ch1.pptch1.ppt
ch1.ppt
 
ch1.ppt
ch1.pptch1.ppt
ch1.ppt
 
ch1.ppt
ch1.pptch1.ppt
ch1.ppt
 
ch1.ppt
ch1.pptch1.ppt
ch1.ppt
 
Operating system introduction
Operating system introductionOperating system introduction
Operating system introduction
 
Ch1
Ch1Ch1
Ch1
 
ch1.pptx
ch1.pptxch1.pptx
ch1.pptx
 
ch1.ppthjhgjhghjghjgjhgugugugmhjgh iyuyuy
ch1.ppthjhgjhghjghjgjhgugugugmhjgh iyuyuych1.ppthjhgjhghjghjgjhgugugugmhjgh iyuyuy
ch1.ppthjhgjhghjghjgjhgugugugmhjgh iyuyuy
 
ch1.ppt
ch1.pptch1.ppt
ch1.ppt
 
ch1.ppt
ch1.pptch1.ppt
ch1.ppt
 
cs8493 - operating systems unit 1
cs8493 - operating systems unit 1cs8493 - operating systems unit 1
cs8493 - operating systems unit 1
 
Linux operating system fundamentals of Operating System
Linux operating system fundamentals of Operating SystemLinux operating system fundamentals of Operating System
Linux operating system fundamentals of Operating System
 
ch1.ppt
ch1.pptch1.ppt
ch1.ppt
 

Recently uploaded

21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx
rahulmanepalli02
 
electrical installation and maintenance.
electrical installation and maintenance.electrical installation and maintenance.
electrical installation and maintenance.
benjamincojr
 
Final DBMS Manual (2).pdf final lab manual
Final DBMS Manual (2).pdf final lab manualFinal DBMS Manual (2).pdf final lab manual
Final DBMS Manual (2).pdf final lab manual
BalamuruganV28
 
Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..
MaherOthman7
 

Recently uploaded (20)

Basics of Relay for Engineering Students
Basics of Relay for Engineering StudentsBasics of Relay for Engineering Students
Basics of Relay for Engineering Students
 
The Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptxThe Entity-Relationship Model(ER Diagram).pptx
The Entity-Relationship Model(ER Diagram).pptx
 
analog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptxanalog-vs-digital-communication (concept of analog and digital).pptx
analog-vs-digital-communication (concept of analog and digital).pptx
 
Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...Fuzzy logic method-based stress detector with blood pressure and body tempera...
Fuzzy logic method-based stress detector with blood pressure and body tempera...
 
Maximizing Incident Investigation Efficacy in Oil & Gas: Techniques and Tools
Maximizing Incident Investigation Efficacy in Oil & Gas: Techniques and ToolsMaximizing Incident Investigation Efficacy in Oil & Gas: Techniques and Tools
Maximizing Incident Investigation Efficacy in Oil & Gas: Techniques and Tools
 
Developing a smart system for infant incubators using the internet of things ...
Developing a smart system for infant incubators using the internet of things ...Developing a smart system for infant incubators using the internet of things ...
Developing a smart system for infant incubators using the internet of things ...
 
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
NEWLETTER FRANCE HELICES/ SDS SURFACE DRIVES - MAY 2024
 
21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx21P35A0312 Internship eccccccReport.docx
21P35A0312 Internship eccccccReport.docx
 
CLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference ModalCLOUD COMPUTING SERVICES - Cloud Reference Modal
CLOUD COMPUTING SERVICES - Cloud Reference Modal
 
Software Engineering Practical File Front Pages.pdf
Software Engineering Practical File Front Pages.pdfSoftware Engineering Practical File Front Pages.pdf
Software Engineering Practical File Front Pages.pdf
 
Intro to Design (for Engineers) at Sydney Uni
Intro to Design (for Engineers) at Sydney UniIntro to Design (for Engineers) at Sydney Uni
Intro to Design (for Engineers) at Sydney Uni
 
electrical installation and maintenance.
electrical installation and maintenance.electrical installation and maintenance.
electrical installation and maintenance.
 
Insurance management system project report.pdf
Insurance management system project report.pdfInsurance management system project report.pdf
Insurance management system project report.pdf
 
Final DBMS Manual (2).pdf final lab manual
Final DBMS Manual (2).pdf final lab manualFinal DBMS Manual (2).pdf final lab manual
Final DBMS Manual (2).pdf final lab manual
 
Filters for Electromagnetic Compatibility Applications
Filters for Electromagnetic Compatibility ApplicationsFilters for Electromagnetic Compatibility Applications
Filters for Electromagnetic Compatibility Applications
 
What is Coordinate Measuring Machine? CMM Types, Features, Functions
What is Coordinate Measuring Machine? CMM Types, Features, FunctionsWhat is Coordinate Measuring Machine? CMM Types, Features, Functions
What is Coordinate Measuring Machine? CMM Types, Features, Functions
 
Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..Maher Othman Interior Design Portfolio..
Maher Othman Interior Design Portfolio..
 
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdflitvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
litvinenko_Henry_Intrusion_Hong-Kong_2024.pdf
 
5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...5G and 6G refer to generations of mobile network technology, each representin...
5G and 6G refer to generations of mobile network technology, each representin...
 
Artificial Intelligence in due diligence
Artificial Intelligence in due diligenceArtificial Intelligence in due diligence
Artificial Intelligence in due diligence
 

chp1_merged.pdf

  • 2. 1.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Chapter 1: Introduction Chapter 1: Introduction „ What Operating Systems Do „ Computer-System Organization „ Computer-System Architecture „ Operating-System Structure „ Operating-System Operations „ Process Management „ Memory Management „ Storage Management „ Protection and Security „ Distributed Systems „ Special-Purpose Systems „ Computing Environments
  • 3. 1.3 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Objectives Objectives „ To provide a grand tour of the major operating systems components „ To provide coverage of basic computer system organization
  • 4. 1.4 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 What is an Operating System? What is an Operating System? „ A program that acts as an intermediary between a user of a computer and the computer hardware. „ Operating system goals: z Execute user programs and make solving user problems easier. z Make the computer system convenient to use. „ Use the computer hardware in an efficient manner.
  • 5. 1.5 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Computer System Structure Computer System Structure „ Computer system can be divided into four components z Hardware – provides basic computing resources CPU, memory, I/O devices z Operating system Controls and coordinates use of hardware among various applications and users z Application programs – define the ways in which the system resources are used to solve the computing problems of the users Word processors, compilers, web browsers, database systems, video games z Users People, machines, other computers
  • 6. 1.6 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Four Components of a Computer System Four Components of a Computer System
  • 7. 1.7 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Operating System Definition Operating System Definition „ OS is a resource allocator z Manages all resources z Decides between conflicting requests for efficient and fair resource use „ OS is a control program z Controls execution of programs to prevent errors and improper use of the computer
  • 8. 1.8 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Operating System Definition (Cont.) Operating System Definition (Cont.) „ No universally accepted definition „ “Everything a vendor ships when you order an operating system” is good approximation z But varies wildly „ “The one program running at all times on the computer” is the kernel. Everything else is either a system program (ships with the operating system) or an application program
  • 9. 1.9 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Computer Startup Computer Startup „ bootstrap program is loaded at power-up or reboot z Typically stored in ROM or EPROM, generally known as firmware z Initializates all aspects of system z Loads operating system kernel and starts execution
  • 10. 1.10 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Computer System Organization Computer System Organization „ Computer-system operation z One or more CPUs, device controllers connect through common bus providing access to shared memory z Concurrent execution of CPUs and devices competing for memory cycles
  • 11. 1.11 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Computer Computer- -System Operation System Operation „ I/O devices and the CPU can execute concurrently. „ Each device controller is in charge of a particular device type. „ Each device controller has a local buffer. „ CPU moves data from/to main memory to/from local buffers „ I/O is from the device to local buffer of controller. „ Device controller informs CPU that it has finished its operation by causing an interrupt.
  • 12. 1.12 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Common Functions of Interrupts Common Functions of Interrupts „ Interrupt transfers control to the interrupt service routine generally, through the interrupt vector, which contains the addresses of all the service routines. „ Interrupt architecture must save the address of the interrupted instruction. „ Incoming interrupts are disabled while another interrupt is being processed to prevent a lost interrupt. „ A trap is a software-generated interrupt caused either by an error or a user request. „ An operating system is interrupt driven.
  • 13. 1.13 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Interrupt Handling Interrupt Handling „ The operating system preserves the state of the CPU by storing registers and the program counter. „ Determines which type of interrupt has occurred: z polling z vectored interrupt system „ Separate segments of code determine what action should be taken for each type of interrupt
  • 14. 1.14 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Interrupt Timeline Interrupt Timeline
  • 15. 1.15 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 I/O Structure I/O Structure „ After I/O starts, control returns to user program only upon I/O completion. z Wait instruction idles the CPU until the next interrupt z Wait loop (contention for memory access). z At most one I/O request is outstanding at a time, no simultaneous I/O processing. „ After I/O starts, control returns to user program without waiting for I/O completion. z System call – request to the operating system to allow user to wait for I/O completion. z Device-status table contains entry for each I/O device indicating its type, address, and state. z Operating system indexes into I/O device table to determine device status and to modify table entry to include interrupt.
  • 16. 1.16 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Two I/O Methods Two I/O Methods Synchronous Asynchronous
  • 17. 1.17 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Device Device- -Status Table Status Table
  • 18. 1.18 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Direct Memory Access Structure Direct Memory Access Structure „ Used for high-speed I/O devices able to transmit information at close to memory speeds. „ Device controller transfers blocks of data from buffer storage directly to main memory without CPU intervention. „ Only one interrupt is generated per block, rather than the one interrupt per byte.
  • 19. 1.19 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Storage Structure Storage Structure „ Main memory – only large storage media that the CPU can access directly. „ Secondary storage – extension of main memory that provides large nonvolatile storage capacity. „ Magnetic disks – rigid metal or glass platters covered with magnetic recording material z Disk surface is logically divided into tracks, which are subdivided into sectors. z The disk controller determines the logical interaction between the device and the computer.
  • 20. 1.20 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Storage Hierarchy Storage Hierarchy „ Storage systems organized in hierarchy. z Speed z Cost z Volatility „ Caching – copying information into faster storage system; main memory can be viewed as a last cache for secondary storage.
  • 21. 1.21 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Storage Storage- -Device Hierarchy Device Hierarchy
  • 22. 1.22 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Caching Caching „ Important principle, performed at many levels in a computer (in hardware, operating system, software) „ Information in use copied from slower to faster storage temporarily „ Faster storage (cache) checked first to determine if information is there z If it is, information used directly from the cache (fast) z If not, data copied to cache and used there „ Cache smaller than storage being cached z Cache management important design problem z Cache size and replacement policy
  • 23. 1.23 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Performance of Various Levels of Storage Performance of Various Levels of Storage „ Movement between levels of storage hierarchy can be explicit or implicit
  • 24. 1.24 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Migration of Integer A from Disk to Register Migration of Integer A from Disk to Register „ Multitasking environments must be careful to use most recent value, no matter where it is stored in the storage hierarchy „ Multiprocessor environment must provide cache coherency in hardware such that all CPUs have the most recent value in their cache „ Distributed environment situation even more complex z Several copies of a datum can exist z Various solutions covered in Chapter 17
  • 25. 1.25 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Operating System Structure Operating System Structure „ Multiprogramming needed for efficiency z Single user cannot keep CPU and I/O devices busy at all times z Multiprogramming organizes jobs (code and data) so CPU always has one to execute z A subset of total jobs in system is kept in memory z One job selected and run via job scheduling z When it has to wait (for I/O for example), OS switches to another job „ Timesharing (multitasking) is logical extension in which CPU switches jobs so frequently that users can interact with each job while it is running, creating interactive computing z Response time should be 1 second z Each user has at least one program executing in memory process z If several jobs ready to run at the same time CPU scheduling z If processes don’t fit in memory, swapping moves them in and out to run z Virtual memory allows execution of processes not completely in memory
  • 26. 1.26 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Memory Layout for Multiprogrammed System Memory Layout for Multiprogrammed System
  • 27. 1.27 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Operating Operating- -System Operations System Operations „ Interrupt driven by hardware „ Software error or request creates exception or trap z Division by zero, request for operating system service „ Other process problems include infinite loop, processes modifying each other or the operating system „ Dual-mode operation allows OS to protect itself and other system components z User mode and kernel mode z Mode bit provided by hardware Provides ability to distinguish when system is running user code or kernel code Some instructions designated as privileged, only executable in kernel mode System call changes mode to kernel, return from call resets it to user
  • 28. 1.28 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Transition from User to Kernel Mode Transition from User to Kernel Mode „ Timer to prevent infinite loop / process hogging resources z Set interrupt after specific period z Operating system decrements counter z When counter zero generate an interrupt z Set up before scheduling process to regain control or terminate program that exceeds allotted time
  • 29. 1.29 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Process Management Process Management „ A process is a program in execution. It is a unit of work within the system. Program is a passive entity, process is an active entity. „ Process needs resources to accomplish its task z CPU, memory, I/O, files z Initialization data „ Process termination requires reclaim of any reusable resources „ Single-threaded process has one program counter specifying location of next instruction to execute z Process executes instructions sequentially, one at a time, until completion „ Multi-threaded process has one program counter per thread „ Typically system has many processes, some user, some operating system running concurrently on one or more CPUs z Concurrency by multiplexing the CPUs among the processes / threads
  • 30. 1.30 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Process Management Activities Process Management Activities The operating system is responsible for the following activities in connection with process management: „ Creating and deleting both user and system processes „ Suspending and resuming processes „ Providing mechanisms for process synchronization „ Providing mechanisms for process communication „ Providing mechanisms for deadlock handling
  • 31. 1.31 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Memory Management Memory Management „ All data in memory before and after processing „ All instructions in memory in order to execute „ Memory management determines what is in memory when z Optimizing CPU utilization and computer response to users „ Memory management activities z Keeping track of which parts of memory are currently being used and by whom z Deciding which processes (or parts thereof) and data to move into and out of memory z Allocating and deallocating memory space as needed
  • 32. 1.32 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Storage Management Storage Management „ OS provides uniform, logical view of information storage z Abstracts physical properties to logical storage unit - file z Each medium is controlled by device (i.e., disk drive, tape drive) Varying properties include access speed, capacity, data- transfer rate, access method (sequential or random) „ File-System management z Files usually organized into directories z Access control on most systems to determine who can access what z OS activities include Creating and deleting files and directories Primitives to manipulate files and dirs Mapping files onto secondary storage Backup files onto stable (non-volatile) storage media
  • 33. 1.33 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Mass Mass- -Storage Management Storage Management „ Usually disks used to store data that does not fit in main memory or data that must be kept for a “long” period of time. „ Proper management is of central importance „ Entire speed of computer operation hinges on disk subsystem and its algorithms „ OS activities z Free-space management z Storage allocation z Disk scheduling „ Some storage need not be fast z Tertiary storage includes optical storage, magnetic tape z Still must be managed z Varies between WORM (write-once, read-many-times) and RW (read- write)
  • 34. 1.34 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 I/O Subsystem I/O Subsystem „ One purpose of OS is to hide peculiarities of hardware devices from the user „ I/O subsystem responsible for z Memory management of I/O including buffering (storing data temporarily while it is being transferred), caching (storing parts of data in faster storage for performance), spooling (the overlapping of output of one job with input of other jobs) z General device-driver interface z Drivers for specific hardware devices
  • 35. 1.35 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Protection and Security Protection and Security „ Protection – any mechanism for controlling access of processes or users to resources defined by the OS „ Security – defense of the system against internal and external attacks z Huge range, including denial-of-service, worms, viruses, identity theft, theft of service „ Systems generally first distinguish among users, to determine who can do what z User identities (user IDs, security IDs) include name and associated number, one per user z User ID then associated with all files, processes of that user to determine access control z Group identifier (group ID) allows set of users to be defined and controls managed, then also associated with each process, file z Privilege escalation allows user to change to effective ID with more rights
  • 36. 1.36 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Computing Environments Computing Environments „ Traditional computer z Blurring over time z Office environment PCs connected to a network, terminals attached to mainframe or minicomputers providing batch and timesharing Now portals allowing networked and remote systems access to same resources z Home networks Used to be single system, then modems Now firewalled, networked
  • 37. 1.37 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Computing Environments (Cont.) Computing Environments (Cont.) „ Client-Server Computing z Dumb terminals supplanted by smart PCs z Many systems now servers, responding to requests generated by clients Compute-server provides an interface to client to request services (i.e. database) File-server provides interface for clients to store and retrieve files
  • 38. 1.38 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Peer Peer- -to to- -Peer Computing Peer Computing „ Another model of distributed system „ P2P does not distinguish clients and servers z Instead all nodes are considered peers z May each act as client, server or both z Node must join P2P network Registers its service with central lookup service on network, or Broadcast request for service and respond to requests for service via discovery protocol z Examples include Napster and Gnutella
  • 39. 1.39 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 12, 2005 Web Web- -Based Computing Based Computing „ Web has become ubiquitous „ PCs most prevalent devices „ More devices becoming networked to allow web access „ New category of devices to manage web traffic among similar servers: load balancers „ Use of operating systems like Windows 95, client-side, have evolved into Linux and Windows XP, which can be clients and servers
  • 40. End of Chapter 1 End of Chapter 1
  • 41. Chapter 2: Operating Chapter 2: Operating- -System Structures System Structures
  • 42. 2.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Chapter 2: Operating Chapter 2: Operating- -System Structures System Structures „ Operating System Services „ User Operating System Interface „ System Calls „ Types of System Calls „ System Programs „ Operating System Design and Implementation „ Operating System Structure „ Virtual Machines „ Operating System Generation „ System Boot
  • 43. 2.3 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Objectives Objectives „ To describe the services an operating system provides to users, processes, and other systems „ To discuss the various ways of structuring an operating system „ To explain how operating systems are installed and customized and how they boot
  • 44. 2.4 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Operating System Services Operating System Services „ One set of operating-system services provides functions that are helpful to the user: z User interface - Almost all operating systems have a user interface (UI) Varies between Command-Line (CLI), Graphics User Interface (GUI), Batch z Program execution - The system must be able to load a program into memory and to run that program, end execution, either normally or abnormally (indicating error) z I/O operations - A running program may require I/O, which may involve a file or an I/O device. z File-system manipulation - The file system is of particular interest. Obviously, programs need to read and write files and directories, create and delete them, search them, list file Information, permission management.
  • 45. 2.5 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Operating System Services (Cont.) Operating System Services (Cont.) „ One set of operating-system services provides functions that are helpful to the user (Cont): z Communications – Processes may exchange information, on the same computer or between computers over a network Communications may be via shared memory or through message passing (packets moved by the OS) z Error detection – OS needs to be constantly aware of possible errors May occur in the CPU and memory hardware, in I/O devices, in user program For each type of error, OS should take the appropriate action to ensure correct and consistent computing Debugging facilities can greatly enhance the user’s and programmer’s abilities to efficiently use the system
  • 46. 2.6 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Operating System Services (Cont.) Operating System Services (Cont.) „ Another set of OS functions exists for ensuring the efficient operation of the system itself via resource sharing z Resource allocation - When multiple users or multiple jobs running concurrently, resources must be allocated to each of them Many types of resources - Some (such as CPU cycles,mainmemory, and file storage) may have special allocation code, others (such as I/O devices) may have general request and release code. z Accounting - To keep track of which users use how much and what kinds of computer resources z Protection and security - The owners of information stored in a multiuser or networked computer system may want to control use of that information, concurrent processes should not interfere with each other Protection involves ensuring that all access to system resources is controlled Security of the system from outsiders requires user authentication, extends to defending external I/O devices from invalid access attempts If a system is to be protected and secure, precautions must be instituted throughout it. A chain is only as strong as its weakest link.
  • 47. 2.7 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 User Operating System Interface User Operating System Interface - - CLI CLI CLI allows direct command entry Sometimes implemented in kernel, sometimes by systems program Sometimes multiple flavors implemented – shells Primarily fetches a command from user and executes it – Sometimes commands built-in, sometimes just names of programs » If the latter, adding new features doesn’t require shell modification
  • 48. 2.8 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 User Operating System Interface User Operating System Interface - - GUI GUI „ User-friendly desktop metaphor interface z Usually mouse, keyboard, and monitor z Icons represent files, programs, actions, etc z Various mouse buttons over objects in the interface cause various actions (provide information, options, execute function, open directory (known as a folder) z Invented at Xerox PARC „ Many systems now include both CLI and GUI interfaces z Microsoft Windows is GUI with CLI “command” shell z Apple Mac OS X as “Aqua” GUI interface with UNIX kernel underneath and shells available z Solaris is CLI with optional GUI interfaces (Java Desktop, KDE)
  • 49. 2.9 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 System Calls System Calls „ Programming interface to the services provided by the OS „ Typically written in a high-level language (C or C++) „ Mostly accessed by programs via a high-level Application Program Interface (API) rather than direct system call use „ Three most common APIs are Win32 API for Windows, POSIX API for POSIX-based systems (including virtually all versions of UNIX, Linux, and Mac OS X), and Java API for the Java virtual machine (JVM) „ Why use APIs rather than system calls? (Note that the system-call names used throughout this text are generic)
  • 50. 2.10 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Example of System Calls Example of System Calls „ System call sequence to copy the contents of one file to another file
  • 51. 2.11 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Example of Standard API Example of Standard API „ Consider the ReadFile() function in the „ Win32 API—a function for reading from a file „ A description of the parameters passed to ReadFile() z HANDLE file—the file to be read z LPVOID buffer—a buffer where the data will be read into and written from z DWORD bytesToRead—the number of bytes to be read into the buffer z LPDWORD bytesRead—the number of bytes read during the last read z LPOVERLAPPED ovl—indicates if overlapped I/O is being used
  • 52. 2.12 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 System Call Implementation System Call Implementation „ Typically, a number associated with each system call z System-call interface maintains a table indexed according to these numbers „ The system call interface invokes intended system call in OS kernel and returns status of the system call and any return values „ The caller need know nothing about how the system call is implemented z Just needs to obey API and understand what OS will do as a result call z Most details of OS interface hidden from programmer by API Managed by run-time support library (set of functions built into libraries included with compiler)
  • 53. 2.13 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 API API – – System Call System Call – – OS Relationship OS Relationship
  • 54. 2.14 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Standard C Library Example Standard C Library Example „ C program invoking printf() library call, which calls write() system call
  • 55. 2.15 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 System Call Parameter Passing System Call Parameter Passing „ Often, more information is required than simply identity of desired system call z Exact type and amount of information vary according to OS and call „ Three general methods used to pass parameters to the OS z Simplest: pass the parameters in registers In some cases, may be more parameters than registers z Parameters stored in a block, or table, in memory, and address of block passed as a parameter in a register This approach taken by Linux and Solaris z Parameters placed, or pushed, onto the stack by the program and popped off the stack by the operating system z Block and stack methods do not limit the number or length of parameters being passed
  • 56. 2.16 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Parameter Passing via Table Parameter Passing via Table
  • 57. 2.17 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Types of System Calls Types of System Calls „ Process control „ File management „ Device management „ Information maintenance „ Communications
  • 58. 2.18 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 MS MS- -DOS execution DOS execution (a) At system startup (b) running a program
  • 59. 2.19 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 FreeBSD Running Multiple Programs FreeBSD Running Multiple Programs
  • 60. 2.20 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 System Programs System Programs „ System programs provide a convenient environment for program development and execution. The can be divided into: z File manipulation z Status information z File modification z Programming language support z Program loading and execution z Communications z Application programs „ Most users’ view of the operation system is defined by system programs, not the actual system calls
  • 61. 2.21 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Solaris 10 Solaris 10 dtrace dtrace Following System Call Following System Call
  • 62. 2.22 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 System Programs System Programs „ Provide a convenient environment for program development and execution z Some of them are simply user interfaces to system calls; others are considerably more complex „ File management - Create, delete, copy, rename, print, dump, list, and generally manipulate files and directories „ Status information z Some ask the system for info - date, time, amount of available memory, disk space, number of users z Others provide detailed performance, logging, and debugging information z Typically, these programs format and print the output to the terminal or other output devices z Some systems implement a registry - used to store and retrieve configuration information
  • 63. 2.23 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 System Programs (cont System Programs (cont’ ’d) d) „ File modification z Text editors to create and modify files z Special commands to search contents of files or perform transformations of the text „ Programming-language support - Compilers, assemblers, debuggers and interpreters sometimes provided „ Program loading and execution- Absolute loaders, relocatable loaders, linkage editors, and overlay-loaders, debugging systems for higher-level and machine language „ Communications - Provide the mechanism for creating virtual connections among processes, users, and computer systems z Allow users to send messages to one another’s screens, browse web pages, send electronic-mail messages, log in remotely, transfer files from one machine to another
  • 64. 2.24 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Operating System Design and Implementation Operating System Design and Implementation „ Design and Implementation of OS not “solvable”, but some approaches have proven successful „ Internal structure of different Operating Systems can vary widely „ Start by defining goals and specifications „ Affected by choice of hardware, type of system „ User goals and System goals z User goals – operating system should be convenient to use, easy to learn, reliable, safe, and fast z System goals – operating system should be easy to design, implement, and maintain, as well as flexible, reliable, error-free, and efficient
  • 65. 2.25 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Operating System Design and Implementation (Cont.) Operating System Design and Implementation (Cont.) „ Important principle to separate Policy: What will be done? Mechanism: How to do it? „ Mechanisms determine how to do something, policies decide what will be done z The separation of policy from mechanism is a very important principle, it allows maximum flexibility if policy decisions are to be changed later
  • 66. 2.26 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Simple Structure Simple Structure „ MS-DOS – written to provide the most functionality in the least space z Not divided into modules z Although MS-DOS has some structure, its interfaces and levels of functionality are not well separated
  • 67. 2.27 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 MS MS- -DOS Layer Structure DOS Layer Structure
  • 68. 2.28 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Layered Approach Layered Approach „ The operating system is divided into a number of layers (levels), each built on top of lower layers. The bottom layer (layer 0), is the hardware; the highest (layer N) is the user interface. „ With modularity, layers are selected such that each uses functions (operations) and services of only lower-level layers
  • 69. 2.29 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Layered Operating System Layered Operating System
  • 70. 2.30 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 UNIX UNIX „ UNIX – limited by hardware functionality, the original UNIX operating system had limited structuring. The UNIX OS consists of two separable parts z Systems programs z The kernel Consists of everything below the system-call interface and above the physical hardware Provides the file system, CPU scheduling, memory management, and other operating-system functions; a large number of functions for one level
  • 71. 2.31 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 UNIX System Structure UNIX System Structure
  • 72. 2.32 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Microkernel System Structure Microkernel System Structure „ Moves as much from the kernel into “user” space „ Communication takes place between user modules using message passing „ Benefits: z Easier to extend a microkernel z Easier to port the operating system to new architectures z More reliable (less code is running in kernel mode) z More secure „ Detriments: z Performance overhead of user space to kernel space communication
  • 73. 2.33 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Mac OS X Structure Mac OS X Structure
  • 74. 2.34 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Modules Modules „ Most modern operating systems implement kernel modules z Uses object-oriented approach z Each core component is separate z Each talks to the others over known interfaces z Each is loadable as needed within the kernel „ Overall, similar to layers but with more flexible
  • 75. 2.35 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Solaris Modular Approach Solaris Modular Approach
  • 76. 2.36 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Virtual Machines Virtual Machines „ A virtual machine takes the layered approach to its logical conclusion. It treats hardware and the operating system kernel as though they were all hardware „ A virtual machine provides an interface identical to the underlying bare hardware „ The operating system creates the illusion of multiple processes, each executing on its own processor with its own (virtual) memory
  • 77. 2.37 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Virtual Machines (Cont.) Virtual Machines (Cont.) „ The resources of the physical computer are shared to create the virtual machines z CPU scheduling can create the appearance that users have their own processor z Spooling and a file system can provide virtual card readers and virtual line printers z A normal user time-sharing terminal serves as the virtual machine operator’s console
  • 78. 2.38 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Virtual Machines (Cont.) Virtual Machines (Cont.) (a) Nonvirtual machine (b) virtual machine Non-virtual Machine Virtual Machine
  • 79. 2.39 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Virtual Machines Virtual Machines (Cont.) (Cont.) „ The virtual-machine concept provides complete protection of system resources since each virtual machine is isolated from all other virtual machines. This isolation, however, permits no direct sharing of resources. „ A virtual-machine system is a perfect vehicle for operating-systems research and development. System development is done on the virtual machine, instead of on a physical machine and so does not disrupt normal system operation. „ The virtual machine concept is difficult to implement due to the effort required to provide an exact duplicate to the underlying machine
  • 80. 2.40 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 VMware VMware Architecture Architecture
  • 81. 2.41 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 The Java Virtual Machine The Java Virtual Machine
  • 82. 2.42 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 Operating System Generation Operating System Generation „ Operating systems are designed to run on any of a class of machines; the system must be configured for each specific computer site „ SYSGEN program obtains information concerning the specific configuration of the hardware system „ Booting – starting a computer by loading the kernel „ Bootstrap program – code stored in ROM that is able to locate the kernel, load it into memory, and start its execution
  • 83. 2.43 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Jan 14, 2005 System Boot System Boot „ Operating system must be made available to hardware so hardware can start it z Small piece of code – bootstrap loader, locates the kernel, loads it into memory, and starts it z Sometimes two-step process where boot block at fixed location loads bootstrap loader z When power initialized on system, execution starts at a fixed memory location Firmware used to hold initial boot code
  • 84. End of Chapter 2 End of Chapter 2
  • 86. 3.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Chapter 3: Processes Chapter 3: Processes „ Process Concept „ Process Scheduling „ Operations on Processes „ Cooperating Processes „ Interprocess Communication „ Communication in Client-Server Systems
  • 87. 3.3 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Process Concept Process Concept „ An operating system executes a variety of programs: z Batch system – jobs z Time-shared systems – user programs or tasks „ Textbook uses the terms job and process almost interchangeably „ Process – a program in execution; process execution must progress in sequential fashion „ A process includes: z program counter z stack z data section
  • 88. 3.4 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Process in Memory Process in Memory
  • 89. 3.5 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Process State Process State „ As a process executes, it changes state z new: The process is being created z running: Instructions are being executed z waiting: The process is waiting for some event to occur z ready: The process is waiting to be assigned to a processor z terminated: The process has finished execution
  • 90. 3.6 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Diagram of Process State Diagram of Process State
  • 91. 3.7 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Process Control Block (PCB) Process Control Block (PCB) Information associated with each process „ Process state „ Program counter „ CPU registers „ CPU scheduling information „ Memory-management information „ Accounting information „ I/O status information
  • 92. 3.8 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Process Control Block (PCB) Process Control Block (PCB)
  • 93. 3.9 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 CPU Switch From Process to Process CPU Switch From Process to Process
  • 94. 3.10 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Process Scheduling Queues Process Scheduling Queues „ Job queue – set of all processes in the system „ Ready queue – set of all processes residing in main memory, ready and waiting to execute „ Device queues – set of processes waiting for an I/O device „ Processes migrate among the various queues
  • 95. 3.11 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Ready Queue And Various I/O Device Queues Ready Queue And Various I/O Device Queues
  • 96. 3.12 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Representation of Process Scheduling Representation of Process Scheduling
  • 97. 3.13 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Schedulers Schedulers „ Long-term scheduler (or job scheduler) – selects which processes should be brought into the ready queue „ Short-term scheduler (or CPU scheduler) – selects which process should be executed next and allocates CPU
  • 98. 3.14 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Addition of Medium Term Scheduling Addition of Medium Term Scheduling
  • 99. 3.15 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Schedulers (Cont.) Schedulers (Cont.) „ Short-term scheduler is invoked very frequently (milliseconds) ⇒ (must be fast) „ Long-term scheduler is invoked very infrequently (seconds, minutes) ⇒ (may be slow) „ The long-term scheduler controls the degree of multiprogramming „ Processes can be described as either: z I/O-bound process – spends more time doing I/O than computations, many short CPU bursts z CPU-bound process – spends more time doing computations; few very long CPU bursts
  • 100. 3.16 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Context Switch Context Switch „ When CPU switches to another process, the system must save the state of the old process and load the saved state for the new process „ Context-switch time is overhead; the system does no useful work while switching „ Time dependent on hardware support
  • 101. 3.17 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Process Creation Process Creation „ Parent process create children processes, which, in turn create other processes, forming a tree of processes „ Resource sharing z Parent and children share all resources z Children share subset of parent’s resources z Parent and child share no resources „ Execution z Parent and children execute concurrently z Parent waits until children terminate
  • 102. 3.18 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Process Creation (Cont.) Process Creation (Cont.) „ Address space z Child duplicate of parent z Child has a program loaded into it „ UNIX examples z fork system call creates new process z exec system call used after a fork to replace the process’ memory space with a new program
  • 103. 3.19 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Process Creation Process Creation
  • 104. 3.20 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 C Program Forking Separate Process C Program Forking Separate Process int main() { pid_t pid; /* fork another process */ pid = fork(); if (pid 0) { /* error occurred */ fprintf(stderr, Fork Failed); exit(-1); } else if (pid == 0) { /* child process */ execlp(/bin/ls, ls, NULL); } else { /* parent process */ /* parent will wait for the child to complete */ wait (NULL); printf (Child Complete); exit(0); } }
  • 105. 3.21 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 A tree of processes on a typical Solaris A tree of processes on a typical Solaris
  • 106. 3.22 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Process Termination Process Termination „ Process executes last statement and asks the operating system to delete it (exit) z Output data from child to parent (via wait) z Process’ resources are deallocated by operating system „ Parent may terminate execution of children processes (abort) z Child has exceeded allocated resources z Task assigned to child is no longer required z If parent is exiting Some operating system do not allow child to continue if its parent terminates – All children terminated - cascading termination
  • 107. 3.23 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Cooperating Processes Cooperating Processes „ Independent process cannot affect or be affected by the execution of another process „ Cooperating process can affect or be affected by the execution of another process „ Advantages of process cooperation z Information sharing z Computation speed-up z Modularity z Convenience
  • 108. 3.24 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Producer Producer- -Consumer Problem Consumer Problem „ Paradigm for cooperating processes, producer process produces information that is consumed by a consumer process z unbounded-buffer places no practical limit on the size of the buffer z bounded-buffer assumes that there is a fixed buffer size
  • 109. 3.25 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Bounded Bounded- -Buffer Buffer – – Shared Shared- -Memory Solution Memory Solution „ Shared data #define BUFFER_SIZE 10 typedef struct { . . . } item; item buffer[BUFFER_SIZE]; int in = 0; int out = 0; „ Solution is correct, but can only use BUFFER_SIZE-1 elements
  • 110. 3.26 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Bounded Bounded- -Buffer Buffer – – Insert() Method Insert() Method while (true) { /* Produce an item */ while (((in = (in + 1) % BUFFER SIZE count) == out) ; /* do nothing -- no free buffers */ buffer[in] = item; in = (in + 1) % BUFFER SIZE; }
  • 111. 3.27 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Bounded Buffer Bounded Buffer – – Remove() Method Remove() Method while (true) { while (in == out) ; // do nothing -- nothing to consume // remove an item from the buffer item = buffer[out]; out = (out + 1) % BUFFER SIZE; return item; }
  • 112. 3.28 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Interprocess Interprocess Communication (IPC) Communication (IPC) „ Mechanism for processes to communicate and to synchronize their actions „ Message system – processes communicate with each other without resorting to shared variables „ IPC facility provides two operations: z send(message) – message size fixed or variable z receive(message) „ If P and Q wish to communicate, they need to: z establish a communication link between them z exchange messages via send/receive „ Implementation of communication link z physical (e.g., shared memory, hardware bus) z logical (e.g., logical properties)
  • 113. 3.29 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Implementation Questions Implementation Questions „ How are links established? „ Can a link be associated with more than two processes? „ How many links can there be between every pair of communicating processes? „ What is the capacity of a link? „ Is the size of a message that the link can accommodate fixed or variable? „ Is a link unidirectional or bi-directional?
  • 114. 3.30 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Communications Models Communications Models
  • 115. 3.31 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Direct Communication Direct Communication „ Processes must name each other explicitly: z send (P, message) – send a message to process P z receive(Q, message) – receive a message from process Q „ Properties of communication link z Links are established automatically z A link is associated with exactly one pair of communicating processes z Between each pair there exists exactly one link z The link may be unidirectional, but is usually bi-directional
  • 116. 3.32 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Indirect Communication Indirect Communication „ Messages are directed and received from mailboxes (also referred to as ports) z Each mailbox has a unique id z Processes can communicate only if they share a mailbox „ Properties of communication link z Link established only if processes share a common mailbox z A link may be associated with many processes z Each pair of processes may share several communication links z Link may be unidirectional or bi-directional
  • 117. 3.33 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Indirect Communication Indirect Communication „ Operations z create a new mailbox z send and receive messages through mailbox z destroy a mailbox „ Primitives are defined as: send(A, message) – send a message to mailbox A receive(A, message) – receive a message from mailbox A
  • 118. 3.34 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Indirect Communication Indirect Communication „ Mailbox sharing z P1, P2, and P3 share mailbox A z P1, sends; P2 and P3 receive z Who gets the message? „ Solutions z Allow a link to be associated with at most two processes z Allow only one process at a time to execute a receive operation z Allow the system to select arbitrarily the receiver. Sender is notified who the receiver was.
  • 119. 3.35 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Synchronization Synchronization „ Message passing may be either blocking or non-blocking „ Blocking is considered synchronous z Blocking send has the sender block until the message is received z Blocking receive has the receiver block until a message is available „ Non-blocking is considered asynchronous z Non-blocking send has the sender send the message and continue z Non-blocking receive has the receiver receive a valid message or null
  • 120. 3.36 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Buffering Buffering „ Queue of messages attached to the link; implemented in one of three ways 1. Zero capacity – 0 messages Sender must wait for receiver (rendezvous) 2. Bounded capacity – finite length of n messages Sender must wait if link full 3. Unbounded capacity – infinite length Sender never waits
  • 121. 3.37 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Client Client- -Server Communication Server Communication „ Sockets „ Remote Procedure Calls „ Remote Method Invocation (Java)
  • 122. 3.38 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Sockets Sockets „ A socket is defined as an endpoint for communication „ Concatenation of IP address and port „ The socket 161.25.19.8:1625 refers to port 1625 on host 161.25.19.8 „ Communication consists between a pair of sockets
  • 123. 3.39 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Socket Communication Socket Communication
  • 124. 3.40 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Remote Procedure Calls Remote Procedure Calls „ Remote procedure call (RPC) abstracts procedure calls between processes on networked systems. „ Stubs – client-side proxy for the actual procedure on the server. „ The client-side stub locates the server and marshalls the parameters. „ The server-side stub receives this message, unpacks the marshalled parameters, and peforms the procedure on the server.
  • 125. 3.41 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Execution of RPC Execution of RPC
  • 126. 3.42 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Remote Method Invocation Remote Method Invocation „ Remote Method Invocation (RMI) is a Java mechanism similar to RPCs. „ RMI allows a Java program on one machine to invoke a method on a remote object.
  • 127. 3.43 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts - 7th Edition, Feb 7, 2006 Marshalling Parameters Marshalling Parameters
  • 128. End of Chapter 3 End of Chapter 3
  • 130. 4.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Chapter 4: Threads Chapter 4: Threads „ Overview „ Multithreading Models „ Threading Issues „ Pthreads „ Windows XP Threads „ Linux Threads „ Java Threads
  • 131. 4.3 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Single and Multithreaded Processes Single and Multithreaded Processes
  • 132. 4.4 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Benefits Benefits „ Responsiveness „ Resource Sharing „ Economy „ Utilization of MP Architectures
  • 133. 4.5 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 User Threads User Threads „ Thread management done by user-level threads library „ Three primary thread libraries: z POSIX Pthreads z Win32 threads z Java threads
  • 134. 4.6 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Kernel Threads Kernel Threads „ Supported by the Kernel „ Examples z Windows XP/2000 z Solaris z Linux z Tru64 UNIX z Mac OS X
  • 135. 4.7 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Multithreading Models Multithreading Models „ Many-to-One „ One-to-One „ Many-to-Many
  • 136. 4.8 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Many Many- -to to- -One One „ Many user-level threads mapped to single kernel thread „ Examples: z Solaris Green Threads z GNU Portable Threads
  • 137. 4.9 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Many Many- -to to- -One Model One Model
  • 138. 4.10 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 One One- -to to- -One One „ Each user-level thread maps to kernel thread „ Examples z Windows NT/XP/2000 z Linux z Solaris 9 and later
  • 139. 4.11 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 One One- -to to- -one Model one Model
  • 140. 4.12 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Many Many- -to to- -Many Model 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
  • 141. 4.13 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Many Many- -to to- -Many Model Many Model
  • 142. 4.14 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Two Two- -level Model level Model „ Similar to M:M, except that it allows a user thread to be bound to kernel thread „ Examples z IRIX z HP-UX z Tru64 UNIX z Solaris 8 and earlier
  • 143. 4.15 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Two Two- -level Model level Model
  • 144. 4.16 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Threading Issues Threading Issues „ Semantics of fork() and exec() system calls „ Thread cancellation „ Signal handling „ Thread pools „ Thread specific data „ Scheduler activations
  • 145. 4.17 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Semantics of fork() and exec() Semantics of fork() and exec() „ Does fork() duplicate only the calling thread or all threads?
  • 146. 4.18 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Thread Cancellation Thread Cancellation „ Terminating a thread before it has finished „ Two general approaches: z Asynchronous cancellation terminates the target thread immediately z Deferred cancellation allows the target thread to periodically check if it should be cancelled
  • 147. 4.19 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Signal Handling 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 „ Options: z Deliver the signal to the thread to which the signal applies z Deliver the signal to every thread in the process z Deliver the signal to certain threads in the process z Assign a specific threa to receive all signals for the process
  • 148. 4.20 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Thread Pools Thread Pools „ Create a number of threads in a pool where they await work „ Advantages: z Usually slightly faster to service a request with an existing thread than create a new thread z Allows the number of threads in the application(s) to be bound to the size of the pool
  • 149. 4.21 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Thread Specific Data Thread Specific Data „ 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)
  • 150. 4.22 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Scheduler Activations Scheduler Activations „ Both M:M and Two-level models require communication to maintain the appropriate number of kernel threads allocated to the application „ Scheduler activations provide upcalls - a communication mechanism from the kernel to the thread library „ This communication allows an application to maintain the correct number kernel threads
  • 151. 4.23 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Pthreads Pthreads „ A POSIX standard (IEEE 1003.1c) API for thread creation and synchronization „ 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)
  • 152. 4.24 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Windows XP Threads Windows XP Threads „ Implements the one-to-one mapping „ Each thread contains z A thread id z Register set z Separate user and kernel stacks z Private data storage area „ The register set, stacks, and private storage area are known as the context of the threads „ The primary data structures of a thread include: z ETHREAD (executive thread block) z KTHREAD (kernel thread block) z TEB (thread environment block)
  • 153. 4.25 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Linux Threads 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)
  • 154. 4.26 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Java Threads Java Threads „ Java threads are managed by the JVM „ Java threads may be created by: z Extending Thread class z Implementing the Runnable interface
  • 155. 4.27 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th edition, Jan 23, 2005 Java Thread States Java Thread States
  • 156. End of Chapter 4 End of Chapter 4
  • 157. Chapter 5: CPU Scheduling Chapter 5: CPU Scheduling
  • 158. 5.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Chapter 5: CPU Scheduling Chapter 5: CPU Scheduling „ Basic Concepts „ Scheduling Criteria „ Scheduling Algorithms „ Multiple-Processor Scheduling „ Real-Time Scheduling „ Thread Scheduling „ Operating Systems Examples „ Java Thread Scheduling „ Algorithm Evaluation
  • 159. 5.3 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Basic Concepts Basic Concepts „ Maximum CPU utilization obtained with multiprogramming „ CPU–I/O Burst Cycle – Process execution consists of a cycle of CPU execution and I/O wait „ CPU burst distribution
  • 160. 5.4 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Alternating Sequence of CPU And I/O Bursts Alternating Sequence of CPU And I/O Bursts
  • 161. 5.5 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Histogram of CPU Histogram of CPU- -burst Times burst Times
  • 162. 5.6 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 CPU Scheduler CPU Scheduler „ Selects from among the processes in memory that are ready to execute, and allocates the CPU to one of them „ CPU scheduling decisions may take place when a process: 1. Switches from running to waiting state 2. Switches from running to ready state 3. Switches from waiting to ready 4. Terminates „ Scheduling under 1 and 4 is nonpreemptive „ All other scheduling is preemptive
  • 163. 5.7 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Dispatcher Dispatcher „ Dispatcher module gives control of the CPU to the process selected by the short-term scheduler; this involves: z switching context z switching to user mode z jumping to the proper location in the user program to restart that program „ Dispatch latency – time it takes for the dispatcher to stop one process and start another running
  • 164. 5.8 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Scheduling Criteria Scheduling Criteria „ CPU utilization – keep the CPU as busy as possible „ Throughput – # of processes that complete their execution per time unit „ Turnaround time – amount of time to execute a particular process „ Waiting time – amount of time a process has been waiting in the ready queue „ Response time – amount of time it takes from when a request was submitted until the first response is produced, not output (for time-sharing environment)
  • 165. 5.9 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Optimization Criteria Optimization Criteria „ Max CPU utilization „ Max throughput „ Min turnaround time „ Min waiting time „ Min response time
  • 166. 5.10 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 First First- -Come, First Come, First- -Served (FCFS) Scheduling Served (FCFS) Scheduling Process Burst Time P1 24 P2 3 P3 3 „ Suppose that the processes arrive in the order: P1 , P2 , P3 The Gantt Chart for the schedule is: „ Waiting time for P1 = 0; P2 = 24; P3 = 27 „ Average waiting time: (0 + 24 + 27)/3 = 17 P1 P2 P3 24 27 30 0
  • 167. 5.11 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 FCFS Scheduling (Cont.) FCFS Scheduling (Cont.) Suppose that the processes arrive in the order P2 , P3 , P1 „ The Gantt chart for the schedule is: „ Waiting time for P1 = 6; P2 = 0; P3 = 3 „ Average waiting time: (6 + 0 + 3)/3 = 3 „ Much better than previous case „ Convoy effect short process behind long process P1 P3 P2 6 3 30 0
  • 168. 5.12 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Shortest Shortest- -Job Job- -First (SJF) Scheduling First (SJF) Scheduling „ Associate with each process the length of its next CPU burst. Use these lengths to schedule the process with the shortest time „ Two schemes: z nonpreemptive – once CPU given to the process it cannot be preempted until completes its CPU burst z preemptive – if a new process arrives with CPU burst length less than remaining time of current executing process, preempt. This scheme is know as the Shortest-Remaining-Time-First (SRTF) „ SJF is optimal – gives minimum average waiting time for a given set of processes
  • 169. 5.13 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Process Arrival Time Burst Time P1 0.0 7 P2 2.0 4 P3 4.0 1 P4 5.0 4 „ SJF (non-preemptive) „ Average waiting time = (0 + 6 + 3 + 7)/4 = 4 Example of Non Example of Non- -Preemptive SJF Preemptive SJF P1 P3 P2 7 3 16 0 P4 8 12
  • 170. 5.14 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Example of Preemptive SJF Example of Preemptive SJF Process Arrival Time Burst Time P1 0.0 7 P2 2.0 4 P3 4.0 1 P4 5.0 4 „ SJF (preemptive) „ Average waiting time = (9 + 1 + 0 +2)/4 = 3 P1 P3 P2 4 2 11 0 P4 5 7 P2 P1 16
  • 171. 5.15 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Determining Length of Next CPU Burst Determining Length of Next CPU Burst „ Can only estimate the length „ Can be done by using the length of previous CPU bursts, using exponential averaging : Define 4. 1 0 , 3. burst CPU next the for value predicted 2. burst CPU of length actual 1. ≤ ≤ = = + α α τ 1 n th n n t ( ) . 1 1 n n n t τ α α τ − + = =
  • 172. 5.16 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Prediction of the Length of the Next CPU Burst Prediction of the Length of the Next CPU Burst
  • 173. 5.17 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Examples of Exponential Averaging Examples of Exponential Averaging „ α =0 z τn+1 = τn z Recent history does not count „ α =1 z τn+1 = α tn z Only the actual last CPU burst counts „ If we expand the formula, we get: τn+1 = α tn+(1 - α)α tn -1 + … +(1 - α )j α tn -j + … +(1 - α )n +1 τ0 „ Since both α and (1 - α) are less than or equal to 1, each successive term has less weight than its predecessor
  • 174. 5.18 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Priority Scheduling Priority Scheduling „ A priority number (integer) is associated with each process „ The CPU is allocated to the process with the highest priority (smallest integer ≡ highest priority) z Preemptive z nonpreemptive „ SJF is a priority scheduling where priority is the predicted next CPU burst time „ Problem ≡ Starvation – low priority processes may never execute „ Solution ≡ Aging – as time progresses increase the priority of the process
  • 175. 5.19 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Round Robin (RR) Round Robin (RR) „ Each process gets a small unit of CPU time (time quantum), usually 10-100 milliseconds. After this time has elapsed, the process is preempted and added to the end of the ready queue. „ If there are n processes in the ready queue and the time quantum is q, then each process gets 1/n of the CPU time in chunks of at most q time units at once. No process waits more than (n-1)q time units. „ Performance z q large ⇒ FIFO z q small ⇒ q must be large with respect to context switch, otherwise overhead is too high
  • 176. 5.20 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Example of RR with Time Quantum = 20 Example of RR with Time Quantum = 20 Process Burst Time P1 53 P2 17 P3 68 P4 24 „ The Gantt chart is: „ Typically, higher average turnaround than SJF, but better response P1 P2 P3 P4 P1 P3 P4 P1 P3 P3 0 20 37 57 77 97 117 121 134 154 162
  • 177. 5.21 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Time Quantum and Context Switch Time Time Quantum and Context Switch Time
  • 178. 5.22 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Turnaround Time Varies With The Time Quantum Turnaround Time Varies With The Time Quantum
  • 179. 5.23 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Multilevel Queue Multilevel Queue „ Ready queue is partitioned into separate queues: foreground (interactive) background (batch) „ Each queue has its own scheduling algorithm z foreground – RR z background – FCFS „ Scheduling must be done between the queues z Fixed priority scheduling; (i.e., serve all from foreground then from background). Possibility of starvation. z Time slice – each queue gets a certain amount of CPU time which it can schedule amongst its processes; i.e., 80% to foreground in RR z 20% to background in FCFS
  • 180. 5.24 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Multilevel Queue Scheduling Multilevel Queue Scheduling
  • 181. 5.25 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Multilevel Feedback Queue Multilevel Feedback Queue „ A process can move between the various queues; aging can be implemented this way „ Multilevel-feedback-queue scheduler defined by the following parameters: z number of queues z scheduling algorithms for each queue z method used to determine when to upgrade a process z method used to determine when to demote a process z method used to determine which queue a process will enter when that process needs service
  • 182. 5.26 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Example of Multilevel Feedback Queue Example of Multilevel Feedback Queue „ Three queues: z Q0 – RR with time quantum 8 milliseconds z Q1 – RR time quantum 16 milliseconds z Q2 – FCFS „ Scheduling z A new job enters queue Q0 which is served FCFS. When it gains CPU, job receives 8 milliseconds. If it does not finish in 8 milliseconds, job is moved to queue Q1. z At Q1 job is again served FCFS and receives 16 additional milliseconds. If it still does not complete, it is preempted and moved to queue Q2.
  • 183. 5.27 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Multilevel Feedback Queues Multilevel Feedback Queues
  • 184. 5.28 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Multiple Multiple- -Processor Scheduling Processor Scheduling „ CPU scheduling more complex when multiple CPUs are available „ Homogeneous processors within a multiprocessor „ Load sharing „ Asymmetric multiprocessing – only one processor accesses the system data structures, alleviating the need for data sharing Processor Affinity: sched_setaffinity() Multicore processors
  • 185. 5.29 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Real Real- -Time Scheduling Time Scheduling „ Hard real-time systems – required to complete a critical task within a guaranteed amount of time „ Soft real-time computing – requires that critical processes receive priority over less fortunate ones Dispatch Latency Interrupt Latency
  • 186. 5.30 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Thread Scheduling Thread Scheduling „ Local Scheduling – How the threads library decides which thread to put onto an available LWP „ Global Scheduling – How the kernel decides which kernel thread to run next Process Contention Scope System Contention Scope
  • 187. 5.31 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Pthread Pthread Scheduling API Scheduling API #include pthread.h #include stdio.h #define NUM THREADS 5 int main(int argc, char *argv[]) { int i; pthread t tid[NUM THREADS]; pthread attr t attr; /* get the default attributes */ pthread attr init(attr); /* set the scheduling algorithm to PROCESS or SYSTEM */ pthread attr setscope(attr, PTHREAD SCOPE SYSTEM); /* set the scheduling policy - FIFO, RT, or OTHER */ pthread attr setschedpolicy(attr, SCHED OTHER); /* create the threads */ for (i = 0; i NUM THREADS; i++) pthread create(tid[i],attr,runner,NULL);
  • 188. 5.32 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Pthread Pthread Scheduling API Scheduling API /* now join on each thread */ for (i = 0; i NUM THREADS; i++) pthread join(tid[i], NULL); } /* Each thread will begin control in this function */ void *runner(void *param) { printf(I am a threadn); pthread exit(0); }
  • 189. 5.33 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Operating System Examples Operating System Examples „ Solaris scheduling „ Windows XP scheduling „ Linux scheduling
  • 190. 5.34 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Solaris 2 Scheduling Solaris 2 Scheduling
  • 191. 5.35 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Solaris Dispatch Table Solaris Dispatch Table
  • 192. 5.36 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Windows XP Priorities Windows XP Priorities
  • 193. 5.37 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Linux Scheduling Linux Scheduling „ Two algorithms: time-sharing and real-time „ Time-sharing z Prioritized credit-based – process with most credits is scheduled next z Credit subtracted when timer interrupt occurs z When credit = 0, another process chosen z When all processes have credit = 0, recrediting occurs Based on factors including priority and history „ Real-time z Soft real-time z Posix.1b compliant – two classes FCFS and RR Highest priority process always runs first
  • 194. 5.38 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 The Relationship Between Priorities and Time The Relationship Between Priorities and Time- -slice length slice length
  • 195. 5.39 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 List of Tasks Indexed According to List of Tasks Indexed According to Prorities Prorities
  • 196. 5.40 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Algorithm Evaluation Algorithm Evaluation „ Deterministic modeling – takes a particular predetermined workload and defines the performance of each algorithm for that workload „ Queueing models „ Implementation
  • 197. 5.41 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 5.15 5.15
  • 198. End of Chapter 5 End of Chapter 5
  • 199. 5.43 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 5.08 5.08
  • 200. 5.44 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 In In- -5.7 5.7
  • 201. 5.45 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 In In- -5.8 5.8
  • 202. 5.46 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 In In- -5.9 5.9
  • 203. 5.47 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Dispatch Latency Dispatch Latency
  • 204. 5.48 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Java Thread Scheduling Java Thread Scheduling „ JVM Uses a Preemptive, Priority-Based Scheduling Algorithm „ FIFO Queue is Used if There Are Multiple Threads With the Same Priority
  • 205. 5.49 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Java Thread Scheduling (cont) Java Thread Scheduling (cont) JVM Schedules a Thread to Run When: 1. The Currently Running Thread Exits the Runnable State 2. A Higher Priority Thread Enters the Runnable State * Note – the JVM Does Not Specify Whether Threads are Time-Sliced or Not
  • 206. 5.50 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Time Time- -Slicing Slicing Since the JVM Doesn’t Ensure Time-Slicing, the yield() Method May Be Used: while (true) { // perform CPU-intensive task . . . Thread.yield(); } This Yields Control to Another Thread of Equal Priority
  • 207. 5.51 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 2, 2005 Thread Priorities Thread Priorities Priority Comment Thread.MIN_PRIORITY Minimum Thread Priority Thread.MAX_PRIORITY Maximum Thread Priority Thread.NORM_PRIORITY Default Thread Priority Priorities May Be Set Using setPriority() method: setPriority(Thread.NORM_PRIORITY + 2);
  • 208. Chapter 6: Process Synchronization Chapter 6: Process Synchronization
  • 209. 6.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Module 6: Process Synchronization Module 6: Process Synchronization „ Background „ The Critical-Section Problem „ Peterson’s Solution „ Synchronization Hardware „ Semaphores „ Classic Problems of Synchronization „ Monitors „ Synchronization Examples „ Atomic Transactions cooperating Competing Process
  • 210. 6.3 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Background Background „ Concurrent access to shared data may result in data inconsistency „ Maintaining data consistency requires mechanisms to ensure the orderly execution of cooperating processes „ Suppose that we wanted to provide a solution to the consumer-producer problem that fills all the buffers. We can do so by having an integer count that keeps track of the number of full buffers. Initially, count is set to 0. It is incremented by the producer after it produces a new buffer and is decremented by the consumer after it consumes a buffer.
  • 211. 6.4 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Producer Producer while (true) { /* produce an item and put in nextProduced */ while (count == BUFFER_SIZE) ; // do nothing buffer [in] = nextProduced; in = (in + 1) % BUFFER_SIZE; count++; } Buffer Count=0 {N} 0 1 2 N-1
  • 212. 6.5 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Consumer Consumer while (true) { while (count == 0) ; // do nothing nextConsumed = buffer[out]; out = (out + 1) % BUFFER_SIZE; count--; /* consume the item in nextConsumed } Count=5
  • 213. 6.6 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Race Condition Race Condition „ count++ could be implemented as register1 = count register1 = register1 + 1 count = register1 „ count-- could be implemented as register2 = count register2 = register2 - 1 count = register2 „ Consider this execution interleaving with “count = 5” initially: S0: producer execute register1 = count {register1 = 5} S1: producer execute register1 = register1 + 1 {register1 = 6} S2: consumer execute register2 = count {register2 = 5} S3: consumer execute register2 = register2 - 1 {register2 = 4} S4: producer execute count = register1 {count = 6 } S5: consumer execute count = register2 {count = 4} 5 6 6 5 4 4
  • 214. 6.7 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Solution to Critical Solution to Critical- -Section Problem Section Problem 1. Mutual Exclusion - If process Pi is executing in its critical section, then no other processes can be executing in their critical sections 2. Progress - If no process is executing in its critical section and there exist some processes that wish to enter their critical section, then the selection of the processes that will enter the critical section next cannot be postponed indefinitely 3. Bounded Waiting - A bound must exist on the number of times that other processes are allowed to enter their critical sections after a process has made a request to enter its critical section and before that request is granted y Assume that each process executes at a nonzero speed y No assumption concerning relative speed of the N processes Entry Section Critical Section Exit Sec Remainder Section P1 P2 P3
  • 215. 6.8 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Peterson Peterson’ ’s Solution s Solution „ Two process solution „ Assume that the LOAD and STORE instructions are atomic; that is, cannot be interrupted. „ The two processes share two variables: z int turn; z Boolean flag[2] „ The variable turn indicates whose turn it is to enter the critical section. „ The flag array is used to indicate if a process is ready to enter the critical section. flag[i] = true implies that process Pi is ready!
  • 216. 6.9 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Algorithm for Process Algorithm for Process P Pi i while (true) { flag[i] = TRUE; turn = j; while ( flag[j] turn == j); CRITICAL SECTION flag[i] = FALSE; REMAINDER SECTION } while(true) { flag[j]= TRUE; turn = i; while( flag[i] turn == i ) ; //waiting CRITICAL SECTION flag[j]= FALSE; REMAINDER SECTION } PROCESS Pj
  • 217. 6.10 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Synchronization Hardware Synchronization Hardware „ Many systems provide hardware support for critical section code „ Uniprocessors – could disable interrupts z Currently running code would execute without preemption z Generally too inefficient on multiprocessor systems Operating systems using this not broadly scalable „ Modern machines provide special atomic hardware instructions Atomic = non-interruptable z Either test memory word and set value z Or swap contents of two memory words
  • 218. 6.11 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 TestAndndSet TestAndndSet Instruction Instruction „ Definition: boolean TestAndSet (boolean *target) { boolean rv = *target; *target = TRUE; return rv: } multiprocess solution Lock
  • 219. 6.12 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Solution using Solution using TestAndSet TestAndSet „ Shared boolean variable lock., initialized to false. „ Solution: while (true) { while ( TestAndSet (lock )) ; /* do nothing // critical section lock = FALSE; // remainder section }
  • 220. 6.13 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Swap Instruction Swap Instruction „ Definition: void Swap (boolean *a, boolean *b) { boolean temp = *a; *a = *b; *b = temp: }
  • 221. 6.14 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Solution using Swap Solution using Swap „ Shared Boolean variable lock initialized to FALSE; Each process has a local Boolean variable key. „ Solution: while (true) { key = TRUE; while ( key == TRUE) Swap (lock, key ); // critical section lock = FALSE; // remainder section }
  • 222. 6.15 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Semaphore Semaphore „ Synchronization tool that does not require busy waiting „ Semaphore S – integer variable „ Two standard operations modify S: wait() and signal() z Originally called P() and V() „ Less complicated „ Can only be accessed via two indivisible (atomic) operations z wait (S) { while S = 0 ; // no-op S--; } z signal (S) { S++; }
  • 223. 6.16 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Semaphore as General Synchronization Tool Semaphore as General Synchronization Tool „ Counting semaphore – integer value can range over an unrestricted domain „ Binary semaphore – integer value can range only between 0 and 1; can be simpler to implement z Also known as mutex locks „ Can implement a counting semaphore S as a binary semaphore „ Provides mutual exclusion z Semaphore S; // initialized to 1 z wait (S); Critical Section signal (S); acquire(){ while( ! available ) ; / waiting available = false; } release(){ available = true; } do{ acquire lock; CS release lock RSection }
  • 224. 6.17 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Semaphore Implementation Semaphore Implementation „ Must guarantee that no two processes can execute wait () and signal () on the same semaphore at the same time „ Thus, implementation becomes the critical section problem where the wait and signal code are placed in the crtical section. z Could now have busy waiting in critical section implementation But implementation code is short Little busy waiting if critical section rarely occupied „ Note that applications may spend lots of time in critical sections and therefore this is not a good solution. p1 p2 p3
  • 225. 6.18 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Semaphore Implementation with no Busy waiting Semaphore Implementation with no Busy waiting „ With each semaphore there is an associated waiting queue. Each entry in a waiting queue has two data items: z value (of type integer) z pointer to next record in the list „ Two operations: z block – place the process invoking the operation on the appropriate waiting queue. z wakeup – remove one of processes in the waiting queue and place it in the ready queue.
  • 226. 6.19 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Semaphore Implementation with no Busy waiting Semaphore Implementation with no Busy waiting (Cont.) (Cont.) „ Implementation of wait: wait (S){ value--; if (value 0) { add this process to waiting queue block(); } } „ Implementation of signal: Signal (S){ value++; if (value = 0) { remove a process P from the waiting queue wakeup(P); } }
  • 227. 6.20 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Deadlock and Starvation Deadlock and Starvation „ Deadlock – two or more processes are waiting indefinitely for an event that can be caused by only one of the waiting processes „ Let S and Q be two semaphores initialized to 1 P0 P1 wait (S); wait (Q); wait (Q); wait (S); . . . . . . signal (S); signal (Q); signal (Q); signal (S); „ Starvation – indefinite blocking. A process may never be removed from the semaphore queue in which it is suspended. Priority Inversion: L M H
  • 228. 6.21 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Classical Problems of Synchronization Classical Problems of Synchronization „ Bounded-Buffer Problem „ Readers and Writers Problem „ Dining-Philosophers Problem Priority inversion: L M H ---- R P3 - H P1- L
  • 229. 6.22 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Bounded Bounded- -Buffer Problem Buffer Problem „ N buffers, each can hold one item „ Semaphore mutex initialized to the value 1 „ Semaphore full initialized to the value 0 „ Semaphore empty initialized to the value N. Buffer [N]
  • 230. 6.23 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Bounded Buffer Problem (Cont.) Bounded Buffer Problem (Cont.) „ The structure of the producer process while (true) { // produce an item wait (empty); wait (mutex); // add the item to the buffer signal (mutex); signal (full); } Buffer[in] = itemp(p) in = (in +1) mod N
  • 231. 6.24 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Bounded Buffer Problem (Cont.) Bounded Buffer Problem (Cont.) „ The structure of the consumer process while (true) { wait (full); wait (mutex); // remove an item from buffer signal (mutex); signal (empty); // consume the removed item }
  • 232. 6.25 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Readers Readers- -Writers Problem Writers Problem „ A data set is shared among a number of concurrent processes z Readers – only read the data set; they do not perform any updates z Writers – can both read and write. „ Problem – allow multiple readers to read at the same time. Only one single writer can access the shared data at the same time. „ Shared Data z Data set z Semaphore mutex initialized to 1. z Semaphore wrt initialized to 1. z Integer readcount initialized to 0.
  • 233. 6.26 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Readers Readers- -Writers Problem (Cont.) Writers Problem (Cont.) „ The structure of a writer process while (true) { wait (wrt) ; // writing is performed signal (wrt) ; }
  • 234. 6.27 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Readers Readers- -Writers Problem (Cont.) Writers Problem (Cont.) „ The structure of a reader process while (true) { wait (mutex) ; readcount ++ ; if (readcount == 1) wait (wrt) ; signal (mutex) // reading is performed wait (mutex) ; readcount - - ; if (readcount == 0) signal (wrt) ; signal (mutex) ; }
  • 235. 6.28 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Dining Dining- -Philosophers Problem Philosophers Problem „ Shared data z Bowl of rice (data set) z Semaphore chopstick [5] initialized to 1
  • 236. 6.29 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Dining Dining- -Philosophers Problem (Cont.) Philosophers Problem (Cont.) „ The structure of Philosopher i: While (true) { wait ( chopstick[i] ); wait ( chopStick[ (i + 1) % 5] ); // eat signal ( chopstick[i] ); signal (chopstick[ (i + 1) % 5] ); // think }
  • 237. 6.30 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Problems with Semaphores Problems with Semaphores „ Incorrect use of semaphore operations: z signal (mutex) …. wait (mutex) z wait (mutex) … wait (mutex) z Omitting of wait (mutex) or signal (mutex) (or both)
  • 238. 6.31 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Monitors Monitors „ A high-level abstraction that provides a convenient and effective mechanism for process synchronization „ Only one process may be active within the monitor at a time monitor monitor-name { // shared variable declarations procedure P1 (…) { …. } … procedure Pn (…) {……} Initialization code ( ….) { … } … } }
  • 239. 6.32 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Schematic view of a Monitor Schematic view of a Monitor
  • 240. 6.33 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Condition Variables Condition Variables „ condition x, y; „ Two operations on a condition variable: z x.wait () – a process that invokes the operation is suspended. z x.signal () – resumes one of processes (if any) that invoked x.wait ()
  • 241. 6.34 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Monitor with Condition Variables Monitor with Condition Variables
  • 242. 6.35 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Solution to Dining Philosophers Solution to Dining Philosophers monitor DP { enum { THINKING; HUNGRY, EATING) state [5] ; condition self [5]; void pickup (int i) { state[i] = HUNGRY; test(i); if (state[i] != EATING) self [i].wait; } void putdown (int i) { state[i] = THINKING; // test left and right neighbors test((i + 4) % 5); test((i + 1) % 5); }
  • 243. 6.36 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Solution to Dining Philosophers (cont) Solution to Dining Philosophers (cont) void test (int i) { if ( (state[(i + 4) % 5] != EATING) (state[i] == HUNGRY) (state[(i + 1) % 5] != EATING) ) { state[i] = EATING ; self[i].signal () ; } } initialization_code() { for (int i = 0; i 5; i++) state[i] = THINKING; } }
  • 244. 6.37 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Solution to Dining Philosophers (cont) Solution to Dining Philosophers (cont) „ Each philosopher I invokes the operations pickup() and putdown() in the following sequence: dp.pickup (i) EAT dp.putdown (i)
  • 245. 6.38 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Monitor Implementation Using Semaphores Monitor Implementation Using Semaphores „ Variables semaphore mutex; // (initially = 1) semaphore next; // (initially = 0) int next-count = 0; „ Each procedure F will be replaced by wait(mutex); … body of F; … if (next-count 0) signal(next) else signal(mutex); „ Mutual exclusion within a monitor is ensured.
  • 246. 6.39 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Monitor Implementation Monitor Implementation „ For each condition variable x, we have: semaphore x-sem; // (initially = 0) int x-count = 0; „ The operation x.wait can be implemented as: x-count++; if (next-count 0) signal(next); else signal(mutex); wait(x-sem); x-count--;
  • 247. 6.40 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Monitor Implementation Monitor Implementation „ The operation x.signal can be implemented as: if (x-count 0) { next-count++; signal(x-sem); wait(next); next-count--; }
  • 248. 6.41 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7th Edition, Feb 8, 2005 Synchronization Examples Synchronization Examples „ Solaris „ Windows XP „ Linux „ Pthreads