2. OPERATING SYSTEMS
i- 2
UNIT-I PROCESSES AND THREADS
Introduction to operating systems-review of computing organization-operating system
structures-system calls-system programs-system structure-virtual machines.
Processes: process concept-process scheduling-Operations on processes-cooperating
processes-Interprocess communication-communication in client-server systems.case
study:IPC in linux.Threads:Multi-threading models-Threading issues case
study:pthreads library
Chapter 1: Introduction
1.1 What is an operating system?
1.2 Mainframe Systems
1.3 Desktop Systems
1.4 Multiprocessor Systems
1.5 Clustered Systems
1.6 Real-Time Systems
1.7 Handheld Systems
1.1 What is an operating system?
An operating system is a program that manages the computer hardware. It also provides a basis
for application programs and acts as an intermediary between a user of a computer and the
computer hardware.
1.1.2 Operating System Definition
OS is a resource allocator
Manages all resources
Decides between conflicting requests for efficient and fair resource use
OS is a control program
Controls execution of programs to prevent errors and improper use of the computer
1.1.3 Computer Startup
Bootstrap program is loaded at power-up or reboot
l Typically stored in ROM or EPROM, generally known as firmware
l Initialized all aspects of system
l Loads operating system kernel and starts execution
l
1.2 Mainframe Systems
Mainframe computer systems were the first computers used to tackle many commercial and
scientific applications.
1. Batch Systems
3. OPERATING SYSTEMS
i- 3
2. Time-Shared systems
1. Batch Systems
1. This operating system usually allows little or no interaction between users and executing
program. The operating system in these early computers was fairly simple.
2. Memory management in batch system is very simple; Memory is usually divided into two
areas one of them is permanently occupied by the resident portion of the operating system
and the other is load programs for execution.
3. When a program terminates a new program is loaded into the same area of memory,
Batch system access to files is serial little protection and no concurrency control of file
access is required.
Disadvantages
1.CPU utilization very less
2.decrease the throughput
3.accessing time is very high
4.waiting time is high
Memory Layout for a simple batch System
Operating system
User program
area
4. OPERATING SYSTEMS
i- 4
Multiprogrammed Systems
1. Multiprogramming increases CPU utilization by organizing jobs so that the cpu always has
one to execute.
2. Operating system picks and begins to execute one of the jobs in the memory.
3. All the jobs that enter the system are kept in the job pool. This pool consists of all
processes residing on disk awaiting allocation of main memory.
4. If several jobs are ready to be brought into memory and if there is not enough room for all
of them, then the system must choose among them, making this decision is job scheduling
5. It’s major task was to transfer control automatically from one job to the next.
Advantages of multiprogramming
o Single user cannot keep CPU and I/O devices busy at all times
o Multiprogramming organizes jobs (code and data) so CPU always has one to
execute
o A subset of total jobs in system is kept in memory
o One job selected and run via job scheduling
o When it has to wait (for I/O for example), OS switches to another job
5. OPERATING SYSTEMS
i- 5
Time-Sharing Systems
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
1. Response time should be < 1 second
2. Each user has at least one program executing in memory process
3. If several jobs ready to run at the same time CPU scheduling
4. If processes don’t fit in memory, swapping moves them in and out to run
5. Virtual memory allows execution of processes not completely in memory
Desktop Systems
o The Apple Macintosh operating system has been ported to more advanced hardware
and how includes new features such as virtual memory and multitasking.
o Microcomputers were immediately able to adopt some of the technology developed
for larger operating systems.
1.4 Multiprocessor Systems
Multiprocessor systems known as parallel systems or tightly coupled systems. Such systems
have more than one processor in close communication
It has three main advantages
1. Increased throughput:
By increasing the number of processors,
To get more work done in less time. The speed-up ratio with n processors in not N. rather it
is less than N.
2. Economy of scale:
Multiprocessor systems can save more money than multiple single-processor systems,
3. Increased reliability:
if the function can be distributed to several processors, then the failure of one processor
will not halt the system, other processor must pick up a share of the work of the failed
processor
6. OPERATING SYSTEMS
i- 6
Symmetric Multiprocessing architecture
Symmetric multiprocessing treats all processors as equals, and I/O can be processed on any
CPU. Asymmetric multiprocessing has one master CPU and the remainder CPUs are slaves.
The master distributes tasks among the slaves and I/O is usually done by the master only.
Asymmetric Multiprocessing architecture
Asymmetric multiprocessing has one master CPU and the remainder CPUs are slaves. The
master distributes tasks among the slaves, and I/O is usually done by the master only.
Distributed Systems
1. A network is a communication path between two or more systems.
2. TCP/IP is the most common network protocol although ATM and other protocols are in
widespread use.
3. To an operating system, a network protocol needs an interface device- a network adapter for
example –with a device driver to manage it ,and software to package data in the
communications protocol to send it and to unpackaged it to receive it
4. LAN->Local area network
5. WAN->wide area network
6. MAN->Metropolitan area network
Client-Server Computing
Dumb terminals supplanted by smart PCs
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
7. OPERATING SYSTEMS
i- 7
Peer-to-Peer Systems
Another model of distributed system
P2P does not distinguish clients and servers
Instead all nodes are considered peers
May each act as client, server or both
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
Examples include Napster and Gnutella
1.5 Clustered Systems
The clustered computers share storage and are closely linked via LAN networking. Clustering is
usually performed to provide high availability.
In asymmetric clustering: one machine is in hot standby mode while the other is running the
applications. The hot standby host (machine) does nothing but monitor the active server.
In symmetric mode: two or more hosts are running efficient as it uses all of the available
hardware. It does require that more than one application be available to run.
1.6 Real-Time Systems
A real-time system has well-defined, fixed time constraints, processing must be done within the
defined constraints, or the system will fail.
1. Hard real-time system
2. Soft real-time system
Hard real time system:
It completes critical tasks on time. This goal requires that all delays in the system be bounded fro
the retrieval of stored data to the time that it takes the operating system to finish any request made
of it.
8. OPERATING SYSTEMS
i- 8
Soft real time system:
Where critical real-time task gets priority over other tasks and retains that priority until it
completes.
Soft real time is an achievable goal that can be mixed with other types of systems.
1.7 Handheld Systems:
It includes Personal digital assistants (PDAS) such as palm pilots or cellular telephones
with connectivity to a network such as the Internet.
PDA is 5 inches in height and 3 inches in width and it weight less than one half pound.
Many handheld devices have between 512kb and 8mb of memory.
Processors for most handheld devices often run at a fraction of the speed of a processor in a
pc. The fast processor in a handheld device would require a larger battery that would have
to be replaced more frequently.
Smaller slower processors which consume less power are typically used. Some hand held
devices may use wireless technology such as blue tooth web browsing.
Web-based computing:
Operating systems like Windows 95, which acted as web clients windows me and windows
2000, which can act as web servers as well as clients.
The web has increased the complexity of devices as their users require them to be web
enabled.
Embedded computing:
Embedded computers are the most prevalent form of computers in existence.
They run embedded real-time operating systems.
These devices are found every where from car engines and manufacturing robots to VCRs
and microwave opens.
The use of embedded system continues to expand.
The power of those devices both as standalone units and as members of networks and the
web issue to increase as well.
9. OPERATING SYSTEMS
i- 9
Chapter 2: Computer-System Structures
2.1 Hardware Protection
Many programming error are detected by the hardware. These errors are normally handled by the
operating system. Whenever a program error occurs the operating system must abnormally
terminate the program so protect the hardware.
Dual mode operation
Two separate modes of operation: user mode and monitor mode.
A bit called the mode bit, is added to the hardware of the computer to indicate the current
mode: monitor (0) or user (1).With the mode bit we are able to distinguish between a task
that is executed behalf of the operating system, and one that is executed on behalf of the
user.
At system boot time, the hardware starts in monitor mode.
The operating system is the loaded, and starts user processes in user mode.
Whenever a trap or interrupt occurs, the hardware switches from user mode to monitor
mode.
The dual mode of operation provides us for protecting the operating system from errant
users, and users from one another.
We accomplish this protection by designating some of the machine instruction that may
cause harm as privileged instructions.
The hardware allows privileged instructions to be executed only in monitor mode. If an
attempt is made to execute a privileged instruction is user mode the hardware does not
execute the instruction but rather treats the instruction as illegal and traps it to the operating
system.
When system, call is executed it is treated by the hardware as software interrupt. Control
passes through the interrupt vector to service routine in the operating system, and the mode
bit is set to monitor mode.
The system call service routine is apart of the operating system. The monitor examines the
interrupting instruction to determine what system call has occurred.
A Parameter indicates what types of service the user program is requesting. Additional
information needed for the request may be passed in register, on the stack, or in memory.
10. OPERATING SYSTEMS
i- 10
I/O protection
To prevent users from performing illegal I/O, we define all I/O instructions to be privileged
instructions.
Users cannot issue I/O instructions directly; they must do it through the operating system.
For I/O protection to be complete, we must be sure that a user program can never gain
control of the computer in monitor mode to be privileged instructions.
Consider a computer executing in user mode. It will switch to monitor mode whenever an
interrupt or trap occurs, jumping to the address determined from the interrupt vector.
If a user program, as part of its execution, stores a new address with an address in the user
program.
Then, when a corresponding trap or interrupt occurred, the hardware would switch to
monitor mode, and would transfer control through the interrupt vector to the user program
.The user program could gain control of the computer in monitor mode. In fact user
programs could gain
Control of the computer in monitor mode in many other ways
user program
Use of a system call to perform I/O
Case n
.
.
.
.
.
.
.
System call n
.
.
Read
2
3
1
11. OPERATING SYSTEMS
i- 11
Memory protection
1. We must provide memory protection at least for the interrupt vector and the interrupt
service routines of the operating system.
2. We want to protect the operating system from access by user programs, and in addition to
protect user program from one another. This protection must be provided by the hardware.
3. To separate each program s memory space, we need the ability to determine the range of
legal addresses that the program may access and to protect the registers (base and limit
register).
4. The base register holds the smallest legal physical memory address.
5. The Limit register contains the size of the range.
Example
If the base register holds 300040 and limit register is 120900, the program can legally access all
addresses from 300040 through 420940 inclusive. This protection is done by the CPU hardware
comparing every address generated in user mode with the registers.
256000
300040
Base register
420940
Limit register
880000
1024000
A base and a limit register define a logical address space
Monitor
Job 1
Job 2
Job 3
Job 4
300040
720980
12. OPERATING SYSTEMS
i- 12
1. Any attempt by a program executing in user mode to access monitor memory or other users
memory in a trap to the monitor, which treats the attempt as a fatal error. This scheme
prevents the code or data structures of either the operating system or other users.
2. The base and limit registers can be loaded by only the operating system, which uses a
special privileged instructions. Since privileged instructions can be executed in only
monitor mode, and since only the operating system can load the base and limit registers.
This scheme allows the monitor to change the value of the registers, but prevents user
programs from changing the registers contents.
3. The operating system executing in monitor mode, is given un restricted access to both
monitor and users’ memory. This provision allows the operating system to load users
program into users memory, to dump out those programs incase of errors, to access and
modify parameters of system calls.
CPU Protection
We must prevent a user program from getting stuck in an infinite loop or not calling system
services, and never returning control to the operating system. To carryout this goal, use the
timer.
Hardware address protection with base and limit registers
CPU
>= <
Base Base+limit
Address Yes Yes
No No
Memory
13. OPERATING SYSTEMS
i- 13
Before turning over control to the user, the operating system ensures that the timer is set to
interrupt.
If the timer interrupts, control transfers automatically to the operating system, which may
treat the interrupt as fatal error or may give the program more time.
A more common use of a timer is to implement time sharing. In the most straightforward
case, the timer could be set to interrupt every N Milliseconds, where N is the time slice that
each user is allowed to execute before the next user gets control of the CPU.
The operating system is invoked at the end of each time slice to perform various
housekeeping tasks, such as adding the value N to the record that specifies the amount of
time the user program has executed thus far.
The operating system also saves registers, internal variable, and buffers, and changes
several other parameters to prepare for the next program to run. This procedure is known as
a context switch.
Chapter 3: Operating-System Structures
System Components
Operating System Services
System Calls
Types of System Calls
System Programs
3.1 Computer System Structure
Computer system can be divided into four components
o Hardware – provides basic computing resources
CPU, memory, I/O devices
o Operating system
Controls and coordinates use of hardware among various applications and
users
o 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
o Users
People, machines, other computers
14. OPERATING SYSTEMS
i- 14
Four Components of a Computer System
3.2 Operating system services
One set of operating-system services provides functions that are helpful to the user:
User interface - Almost all operating systems have a user interface (UI)
Varies between Command-Line (CLI), Graphics User Interface (GUI), Batch
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)
I/O operations - A running program may require I/O, which may involve a file or an
I/O device.
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.
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)
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
Another set of OS functions exists for ensuring the efficient operation of the system itself via
resource sharing
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.
15. OPERATING SYSTEMS
i- 15
Accounting - To keep track of which users use how much and what kinds of computer
resources
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.
3.3 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)
Example of System Calls
System call sequence to copy the contents of one file to another file
16. OPERATING SYSTEMS
i- 16
System Call Parameter Passing
1. Often, more information is required than simply identity of desired system call
2. Exact type and amount of information vary according to OS and call
Three general methods used to pass parameters to the OS
1. Simplest: pass the parameters in registers
2. In some cases, may be more parameters than registers 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
3. Parameters placed, or pushed, onto the stack by the program and popped off the stack by
the operating system
4. Block and stack methods do not limit the number or length of parameters being passed
Parameter Passing via Table
Types of System Calls
1. Process control
2. File management
3. Device management
4. Information maintenance
5. Communications
17. OPERATING SYSTEMS
i- 17
1.process control
1. End,abort
2. Load,execute
3. Create process,terminate process
4. Get process attributes ,set attributes
5. Wait for time
6. Wait event,singnal event
Example
MS-DOS execution
a) At system startup (b) running a program
FreeBSD Running Multiple Programs
18. OPERATING SYSTEMS
i- 18
2. File Management
1. need to be able to create and delete files
2. once the file is created, need to open it and to execute it
3. read ,write or reposition
4. need to close it
System calls
Create file, delete file
Open, close
Read, write reposition
Get file attributes, set file attributes
3. Device Management
A program as it is running may need additional resources to proceed. Resources may be more
memory, tap drivers access to files.
Files can be thought of as abstract or virtual devices. the device has been requested, we can read,
write and reposition the device
4. Information maintenance
System calls
Get time or date, set time or date
Get system date, set system data
Get process, file or device attributes
Set process file or device attributes
Systems have a system call to return the current time and date .other system calls may return
information about the system. The number of current users, the version number of the operating
system the amount if free memory or disk space
5. Communications
System calls
1. Create, delete communication connection
2. Send, receive messages
3. Transfer status information
4. Attach or detach remote devices
Two common models
1. The message passing model
2. Shared memory model
Message passing model
Information is exchanged through an interprocess communication facility provides by the
operating system.
19. OPERATING SYSTEMS
i- 19
Connection must be opened.
Get host id->to get host name
Get process id->to get process name
The source of the communication known as the client and the receiving daemon, known as s server
the exchanges message by read message and write message system call close connection call
terminates the communication.
Shared-memory model
Process use map memory system calls to gain access to regions of memory owned
The operating system tries to prevent one process from accessing another process memory.
Shared memory requires that several process agree to remove this restriction. They may
exchange information by reading and writing data in theses shared areas.
The form of the data and the location determined by these process and are not under the
operating system’s control
3.4 System Programs
System programs provide a convenient environment for program development and
execution. The can be divided into:
File manipulation
Status information
File modification
Programming language support
Program loading and execution
Communications
Application programs
Most users’ view of the operation system is defined by system programs, not the
actual system calls
Provide a convenient environment for program development and execution
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
Some ask the system for info - date, time, amount of available memory, disk space, and
number of users
Others provide detailed performance, logging, and debugging information
20. OPERATING SYSTEMS
i- 20
Typically, these programs format and print the output to the terminal or other output
devices
Some systems implement a registry - used to store and retrieve configuration
information
File modification
o Text editors to create and modify files
o 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
o 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
Chapter 4: Processes
1. Process Concept
2. Process Scheduling
3. Operations on Processes
4. Cooperating Processes
5. Interprocess Communication
4.1 Process Concept
An operating system executes a variety of programs:
Batch system – jobs
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:
Program counter
Stack
Data section
21. OPERATING SYSTEMS
i- 21
Process in Memory
As a process executes, it changes state
a. new: The process is being created
b. running: Instructions are being executed
c. waiting: The process is waiting for some event to occur
d. ready: The process is waiting to be assigned to a processor
e. terminated: The process has finished execution
Diagram of Process State
22. OPERATING SYSTEMS
i- 22
Information associated with each process
Process state
Program counter
CPU registers
CPU scheduling information
Memory-management information
Accounting information
I/O status information
Process Control Block (PCB)
1. Process id : identification number of any process
2. Process state: The state may be new, ready, running waiting, halted, and so on.
3. Program counter: the counter indicates the address of the next instruction to be executed
for this process.
4. CPU registers: the registers vary in number and type, depending on the computer
architecture. The include accumulators, index registers, stack, pointers and general purpose
registers, plus any condition-code information. Along with the program counter, this state
information must be saved.
5. CPU scheduling information: this information includes a process priority, pointers to
scheduling queues, and any other scheduling parameters.
6. Memory –management information: this information may include such information as
the value base and limit registers, the page tables or segment tables, depending on the
memory system used by the operating system
23. OPERATING SYSTEMS
i- 23
7. Accounting information: this information includes the amount of CPU and real time used,
time limits, account numbers, job or process numbers and so on.
8. I/O status information: the information includes the list of I/O devices allocated to this
process, a list of open files and so on.
4.2 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
Ready Queue and Various I/O Device Queues
24. OPERATING SYSTEMS
i- 24
Representation of Process Scheduling
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
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:
25. OPERATING SYSTEMS
i- 25
I/O-bound process – spends more time doing I/O than computations, many short CPU
bursts
CPU-bound process – spends more time doing computations; few very long CPU
bursts
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
4.3 Process Creation
Parent process create children processes, which, in turn create other processes, forming a tree
of processes
Resource sharing
Parent and children share all resources
Children share subset of parent’s resources
Parent and child share no resources
Execution
Parent and children execute concurrently
Parent waits until children terminate
Process Creation (Cont.)
Address space
Child duplicate of parent
Child has a program loaded into it
UNIX examples
fork system call creates new process
exec system call used after a fork to replace the process’ memory space with a new
program
# include <stdio.h>
void main(int argc ,char *argv[])
{
int pid;
/* for another process */
pid=fork();
if(pid<0){
/* error occurred */
fprintf(stderr, ”fork failed “);
26. OPERATING SYSTEMS
i- 26
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);
}
}
Process Termination
Process executes last statement and asks the operating system to delete it (exit)
Output data from child to parent (via wait)
Process’ resources are deal located by operating system
Parent may terminate execution of children processes (abort)
Child has exceeded allocated resources
Task assigned to child is no longer required
If parent is exiting
Some operating system do not allow child to continue if its parent terminates
All children terminated - cascading termination
27. OPERATING SYSTEMS
i- 27
4.4 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
Information sharing
Computation speed-up
Modularity
Convenience
1. Information sharing: since several users may be interested in the same piece of
information we must provide an environment to allow concurrent access to these types
of resources.
2. Computation speedup: if we want a particular task to run faster, we must break it into
subtasks, each of which will be executing in parallel with the others; such a speedup
can be achieved only if the computer has multiple processing elements.
3. Modularity: We may want to construct the system in a modular fashion, dividing the
system functions into separate processes or threads.
4. Convenience: even an individual user may have many tasks on which to work at one
time .For instance, a user may be editing, printing, and compiling in parallel
Producer-Consumer Problem
Paradigm for cooperating processes, producer process produces information that is consumed
by a consumer process
Unbounded-buffer places no practical limit on the size of the buffer
Bounded-buffer assumes that there is a fixed buffer size
Bounded-Buffer – Shared-Memory Solution
Shared data
#define BUFFER_SIZE 10
typedef struct {
. . .
} item;
Bounded-Buffer – Insert () Method
item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
28. OPERATING SYSTEMS
i- 28
Solution is correct, but can only use BUFFER_SIZE-1 elements
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;
}
Bounded Buffer – 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;
}
4.5 Interprocess 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:
send(message) – message size fixed or variable
receive(message)
If P and Q wish to communicate, they need to:
establish a communication link between them
exchange messages via send/receive
Implementation of communication link
physical (e.g., shared memory, hardware bus)
logical (e.g., logical properties)
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?
29. OPERATING SYSTEMS
i- 29
Communications Models
Message passing model (a) Shared memory model(b)
Direct Communication
Processes must name each other explicitly:
send (P, message) – send a message to process P
receive(Q, message) – receive a message from process Q
Properties of communication link
Links are established automatically
A link is associated with exactly one pair of communicating processes
Between each pair there exists exactly one link
The link may be unidirectional, but is usually bi-directional
Messages are directed and received from mailboxes (also referred to as ports)
Each mailbox has a unique id
Processes can communicate only if they share a mailbox
Properties of communication link
Link established only if processes share a common mailbox
A link may be associated with many processes
Each pair of processes may share several communication links
Link may be unidirectional or bi-directional
30. OPERATING SYSTEMS
i- 30
Operations
o create a new mailbox
o send and receive messages through mailbox
o 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
Indirect Communication
Mailbox sharing
o P1, P2, and P3 share mailbox A
o P1, sends; P2 and P3 receive
o Who gets the message?
Solutions
o Allow a link to be associated with at most two processes
o Allow only one process at a time to execute a receive operation
o Allow the system to select arbitrarily the receiver. Sender is notified who the
receiver was.
Synchronization
Message passing may be either blocking or non-blocking
Blocking is considered synchronous
o Blocking send has the sender block until the message is received
o Blocking receive has the receiver block until a message is available
Non-blocking is considered asynchronous
o Non-blocking send has the sender send the message and continue
o Non-blocking receive has the receiver receive a valid message or null
Buffering
Queue of messages attached to the link; implemented in one of three ways
Zero capacity – 0 messages
Sender must wait for receiver (rendezvous)
Bounded capacity – finite length of n messages
Sender must wait if link full
Unbounded capacity – infinite length
Sender never waits
31. OPERATING SYSTEMS
i- 31
Chapter 5: Threads
1. Overview
2. Threading Issues
5.1 Overview
Definition: A thread, sometimes called a lightweight process (LWP), is a basic unit of
CPU utilization; it comprises a thread ID, a program counter, a register set, and stack .It
shares with other threads belonging to the same process its code and signals.
Process: A traditional (or heavyweight) process has s single thread of one task at a time.
Single and Multithreaded Processes
Single threaded processes, it would be able to service only one client at time
Multithreaded processes, it would be able to service several of clients concurrently
accessing it.
Per process items Per thread items
Address space
Global variable
Open files
Child processes
Pending alarms
Signals and signal handlers
Accounting information
Program counter
Registers
Stack
status
32. OPERATING SYSTEMS
i- 32
Benefits
1. Responsiveness: Multi threading an interactive3 application may allow a program to
continue running even if part of it us blocked or is performing a length operating, thereby
increasing responsiveness to the user. For instance, a multithreaded web browser could
still allow user interaction in one thread while an image is being loaded in another thread.
2. Resource Sharing: By default, threads share the memory and the resources of the
process to which they belong. The benefit of code sharing is that it allows an application
to have several different threads of activity all within the same address space.
3. Economy : Allocating memory and resources for process creation is costly .alternatively,
because threads share resources of the process to which they belong, it is more
economical to create and context switch threads. It can be difficult to gauge empirically
the difference in overhead for creating and maintaining a process rather than a thread, but
un general it is much more time consuming to create and mange processes than threads.
4. Utilization of MP Architectures: The benefits of multi threading can be greatly
increased in multiprocessor architecture, where each thread may be running in parallel on
adifferent processor. A single-threaded process can only run on one CPU, no matter how
many are available. Multithreading on a multi-CPU machine increases concurrency.
User Threads
Thread management done by user-level threads library
The library provides support for thread creation, scheduling and management with no support
of kernel.
Three primary thread libraries:
POSIX Pthreads
Win32 threads
Java threads
Kernel Threads
It is supported by the operating system. The kernel performs thread creation, scheduling and
management in kernel space. Thread management is done by the operating system, kernel
threads are slower to create and manage than are user threads.
Examples
Windows XP/2000
Solaris
Linux
Tru64 UNIX
Mac OS X
33. OPERATING SYSTEMS
i- 33
Multithreading Models
Many-to-One
One-to-One
Many-to-Many
Many-to-One
Many user-level threads mapped to single kernel thread
Thread management is done in user space, so it is efficient but the entire process will block if a
thread makes a blocking system call.
Examples:
Solaris Green Threads
GNU Portable Threads
Many-to-One Model
One-to-One
Each user-level thread maps to kernel thread
It provides more concurrency than the many-to one model by allowing another thread to run
when a thread makes a blocking system call. It allows multiple threads to run in parallel on
Multiprocessors.
Drawback:
It is creating a user threads requires creating corresponding kernel thread
Examples
Windows NT/XP/2000
Linux
Solaris 9 and later
34. OPERATING SYSTEMS
i- 34
One-to-one Model
Many-to-Many Model
Allows many user level threads to be mapped to many kernel threads
Allows the operating system to create a sufficient number of kernel threads
Solaris prior to version 9
Windows NT/2000 with the ThreadFiber package
Many-to-Many Model
35. OPERATING SYSTEMS
i- 35
Two-level Model
Similar to M:M, except that it allows a user thread to be bound to kernel thread
Examples
IRIX
HP-UX
Tru64 UNIX
Solaris 8 and earlier
Two-level Model
5.2 Threading Issues
1. Semantics of fork() and exec() system calls
2. Thread cancellation
3. Signal handling
4. Thread pools
5. Thread specific data
6. Scheduler activations
Semantics of fork() and exec()
Fork() system call is used to create thread and exec system call is used to execute a thread
Thread Cancellation
Terminating a thread before it has finished
Two general approaches:
Asynchronous cancellation terminates the target thread immediately
Deferred cancellation allows the target thread to periodically check if it should be
cancelled
36. OPERATING SYSTEMS
i- 36
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
Signal is generated by particular event
Signal is delivered to a process
Signal is handled
Options:
Deliver the signal to the thread to which the signal applies
Deliver the signal to every thread in the process
Deliver the signal to certain threads in the process
Assign a specific thread to receive all signals for the process
Create a number of threads in a pool where they await work
Advantages:
Usually slightly faster to service a request with an existing thread than create a new
thread
Allows the number of threads in the application(s) to be bound to the size of the pool
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)
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 up calls - a communication mechanism from the kernel to the
thread library
This communication allows an application to maintain the correct number kernel threads
*********************************