Module 2.1,2.2
Module 2.1,2.2
By
Prof. Sagar D. Korde
Department of Information Technology
K J Somaiya College of Engineering, Mumbai-77
(Constituent college of Somaiya Vidyavihar University)
9/3/2020 Silberschatz A., Galvin P., Gagne G, “Operating Systems Concepts”, VIIIth Edition, Wiley, 2011. 1
Course Outcomes:
At the end of successful completion of the module a student will be able to
CO2: Demonstrate use of inter process communication.
Module 2: Process Management
2.1 Processes: Process Concept, process creation , suspension and termination ,Process States: 2, 5, 7
state models, Process Description, Process Control block.
2.2 Threads: Multithreading models, Thread implementations – user level and kernel level threads,
Symmetric Multiprocessing.
2.3 Uniprocessor Scheduling: Scheduling Criteria, Types of Scheduling: Preemptive, Non-preemptive,
Long-term, Medium- term, Short-term schedulers. Scheduling Algorithms: FCFS, SJF, SRTF,RR, Priority.
2.4 Multiprocessor Scheduling: Granularity, Design Issues, Process Scheduling. Thread Scheduling,
Real Time Scheduling
2.5 Process Security
9/3/2020 Silberschatz A., Galvin P., Gagne G, “Operating Systems Concepts”, VIIIth Edition, Wiley, 2011. 2
2.1 Processes: Outline
• Process Concept
• Process Scheduling
• Operations on Processes
• Interprocess Communication
• Examples of IPC Systems
• Communication in Client-Server Systems
9/3/2020 3
Process Concept
• An operating system executes a variety of programs:
o Batch system – jobs
o Time-shared systems – user programs or tasks
• A process includes:
o program counter
o stack
o data section
9/3/2020 4
The Process
• Multiple parts
o The program code, also called text section
o Current activity including program counter, processor registers
o Stack containing temporary data
−Function parameters, return addresses, local variables
o Data section containing global variables
o Heap containing memory dynamically allocated during run time
• Program is passive entity, process is active
o Program becomes process when executable file loaded into memory
• Execution of program started via GUI mouse clicks, command line entry of its name, etc
• One program can be several processes
o Consider multiple users executing the same program
9/3/2020 5
Process in Memory
9/3/2020 6
Process State
• As a process executes, it changes state
o new: The process is being created
o running: Instructions are being executed
o waiting: The process is waiting for some event to occur
o ready: The process is waiting to be assigned to a processor
o terminated: The process has finished execution
9/3/2020 7
Diagram of Process State
9/3/2020 8
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
9/3/2020 9
Process Control Block (PCB)
9/3/2020 10
CPU Switch From Process to Process
9/3/2020 11
Process Scheduling
• Maximize CPU use, quickly switch processes onto CPU for time sharing
• Process scheduler selects among available processes for next execution on
CPU
• Maintains scheduling queues of processes
o Job queue – set of all processes in the system
o Ready queue – set of all processes residing in main memory, ready
and waiting to execute
o Device queues – set of processes waiting for an I/O device
o Processes migrate among the various queues
9/3/2020 12
Process Representation in Linux
9/3/2020 13
Ready Queue And Various
I/O Device Queues
9/3/2020 14
Representation of Process Scheduling
9/3/2020 15
Schedulers
9/3/2020 16
Schedulers (Cont.)
9/3/2020 17
Addition of Medium Term Scheduling
9/3/2020 18
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 via a context switch.
• Context of a process represented in the PCB
• Context-switch time is overhead; the system does no useful work while
switching
o The more complex the OS and the PCB -> longer the context switch
• Time dependent on hardware support
o Some hardware provides multiple sets of registers per CPU -> multiple
contexts loaded at once
9/3/2020 19
Process Creation
• Parent process create children processes, which, in turn create other processes,
forming a tree of processes
• Generally, process identified and managed via a process identifier (pid)
• Resource sharing
o Parent and children share all resources
o Children share subset of parent’s resources
o Parent and child share no resources
• Execution
o Parent and children execute concurrently
o Parent waits until children terminate
9/3/2020 20
Process Creation (Cont.)
• Address space
o Child duplicate of parent
o Child has a program loaded into it
• UNIX examples
o fork system call creates new process
o exec system call used after a fork to replace the process’ memory
space with a new program
9/3/2020 21
Process Creation
9/3/2020 22
C Program Forking Separate Process
#include <stdio.h> #include <stdio.h> #include <stdio.h>
#include <sys/types.h> #include <sys/types.h> #include <ctype.h>
#include <unistd.h> int main() #include <limits.h>
int main() { #include <string.h>
{ fork(); #include <stdlib.h>
fork(); #include <unistd.h>
// make two process which run same fork();
// program after this instruction printf("hello\n"); int main()
fork(); return 0; {
} int pid;
printf("Hello world!\n"); pid=fork();
return 0;
} if (pid==0) {
printf("I am the child\n");
printf("my pid=%d\n", getpid());
}
return 0;
}
9/3/2020 23
A Tree of Processes
9/3/2020 24
Process Termination
• Process executes last statement and asks the operating system to delete it (exit)
o Output data from child to parent (via wait)
o Process’ resources are deallocated by operating system
• Parent may terminate execution of children processes (abort)
o Child has exceeded allocated resources
o Task assigned to child is no longer required
o If parent is exiting
−Some operating system do not allow child to continue if its parent
terminates
• All children terminated - cascading termination
9/3/2020 25
Interprocess Communication
• Processes within a system may be independent or cooperating
• Cooperating process can affect or be affected by other processes, including
sharing data
• Reasons for cooperating processes:
o Information sharing
o Computation speedup
o Modularity
o Convenience
• Cooperating processes need interprocess communication (IPC)
• Two models of IPC
o Shared memory
o Message passing
9/3/2020 26
Communications Models
9/3/2020 27
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
o Information sharing
o Computation speed-up
o Modularity
o Convenience
9/3/2020 28
Producer-Consumer Problem
9/3/2020 29
Bounded-Buffer –
Shared-Memory Solution
• Shared data
#define BUFFER_SIZE 10
typedef struct {
...
} item;
item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
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;
}
9/3/2020 31
Bounded Buffer – Consumer
while (true) {
while (in == out)
; // do nothing -- nothing to consume
9/3/2020 32
Interprocess Communication –
Message Passing
• 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:
o send(message) – message size fixed or variable
o receive(message)
• If P and Q wish to communicate, they need to:
o establish a communication link between them
o exchange messages via send/receive
• Implementation of communication link
o physical (e.g., shared memory, hardware bus)
o logical (e.g., logical properties)
9/3/2020 33
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?
9/3/2020 34
Direct Communication
• Processes must name each other explicitly:
o send (P, message) – send a message to process P
o receive(Q, message) – receive a message from process Q
9/3/2020 35
Indirect Communication
• Messages are directed and received from mailboxes (also referred to as ports)
o Each mailbox has a unique id
o Processes can communicate only if they share a mailbox
9/3/2020 36
Indirect Communication
• Operations
o create a new mailbox
o send and receive messages through mailbox
o destroy a mailbox
9/3/2020 37
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.
9/3/2020 38
Synchronization
9/3/2020 39
Buffering
9/3/2020 40
Examples of IPC Systems - POSIX
• POSIX Shared Memory
o Process first creates shared memory segment
segment id = shmget(IPC PRIVATE, size, S IRUSR | S
IWUSR);
o Process wanting access to that shared memory must attach to it
shared memory = (char *) shmat(id, NULL, 0);
o Now the process could write to the shared memory
sprintf(shared memory, "Writing to shared memory");
o When done a process can detach the shared memory from its address space
shmdt(shared memory);
9/3/2020 41
Examples of IPC Systems - Mach
9/3/2020 42
Examples of IPC Systems – Windows XP
9/3/2020 43
Local Procedure Calls in Windows XP
9/3/2020 44
Communications in Client-Server Systems
• Sockets
• Pipes
9/3/2020 45
Sockets
9/3/2020 46
Socket Communication
9/3/2020 47
Remote Procedure Calls
• The client-side stub locates the server and marshalls the parameters
9/3/2020 48
Execution of RPC
9/3/2020 49
Pipes
• Issues
o Is communication unidirectional or bidirectional?
o In the case of two-way communication, is it half or full-duplex?
o Must there exist a relationship (i.e. parent-child) between the
communicating processes?
o Can the pipes be used over a network?
9/3/2020 50
Ordinary Pipes
• Ordinary Pipes allow communication in standard producer-
consumer style
• Consumer reads from the other end (the read-end of the pipe)
9/3/2020 51
Ordinary Pipes
9/3/2020 52
Named Pipes
• Named Pipes are more powerful than ordinary pipes
• Communication is bidirectional
9/3/2020 53
2.2 Threads : Outline
• Overview
• Multithreading Models
• Thread Libraries
• Threading Issues
• Operating System Examples
• Windows XP Threads
• Linux Threads
9/3/2020 54
Thread Overview
• Threads are mechanisms that permit an application to perform multiple tasks
concurrently.
9/3/2020 55
Single and Multithreaded Processes
9/3/2020 56
Threads in Memory
Memory is allocated for a process in segments or parts:
argv, environment
Stack for main thread
Increasing virtual address
Heap
Un-initialized data
Initialized data
Text ( program code)
9/3/2020 58
Benefits
Responsiveness
Interactive application can delegate background functions to a thread and keep running
Resource Sharing
Several different threads can access the same address space
Economy
Allocating memory and new processes is costly. Threads are much ‘cheaper’ to initiate.
Scalability
Use threads to take advantage of multiprocessor architecture
9/3/2020 59
Multithreaded Server Architecture
thread
thread
thread
thread
9/3/2020 60
Multicore Programming
9/3/2020 61
Multicore Programming
• Multicore systems putting pressure on programmers, challenges include
o Dividing activities
−What tasks can be separated to run on different processors
o Balance
−Balance work on all processors
o Data splitting
−Separate data to run with the tasks
o Data dependency
−Watch for dependences between tasks
o Testing and debugging
−Harder!!!!
9/3/2020 62
Threads Assist Multicore Programming
thread
thread
thread
9/3/2020 63
Multithreading Models
Support provided at either
9/3/2020 64
User Threads
• Thread management done by user-level threads library
9/3/2020 65
Kernel Threads
• Supported by the Kernel
• Examples
o Windows XP/2000
o Solaris
o Linux
o Tru64 UNIX
o Mac OS X
9/3/2020 66
Multithreading Models
• Many-to-One
• One-to-One
• Many-to-Many
9/3/2020 67
Many-to-One
9/3/2020 68
One-to-One
9/3/2020 69
Many-to-Many Model
9/3/2020 70
Thread Libraries
• Thread library provides programmer with API for creating and managing
threads
9/3/2020 71
Thread Libraries
9/3/2020 72
POSIX Compilation on Linux
On Linux, programs that use the Pthreads API must be compiled with
–pthread or –lpthread
9/3/2020 73
POSIX: Thread Creation
#include <pthread.h>
9/3/2020 74
POSIX: Thread ID
#include <pthread.h>
pthread_t pthread_self()
9/3/2020 75
POSIX: Wait for Thread Completion
#include <pthread.h>
9/3/2020 76
POSIX: Thread Termination
#include <pthread.h>
9/3/2020 77
Thread Cancellation
9/3/2020 78
Thread Cancellation
9/3/2020 79
Thread Cancellation
9/3/2020 80
Thread Termination: Cleanup Handlers
9/3/2020 81
Threading Issues
9/3/2020 82
Semantics of fork() ,exec(), exit()
Does fork() duplicate only the calling thread or all threads?
9/3/2020 83
Semantics of fork() ,exec(), exit()
Threads and fork()
When a multithread process calls fork(), only the calling thread is replicated. All other threads
vanish in the child. No thread-specific data destructors or cleanup handlers are executed.
Problems:
The global data may be inconsistent:
−Was another thread in the process of updating it?
−Data or critical code may be locked by another thread. That lock is copied into child process, too.
Memory leaks
Thread (other) specific data not available
9/3/2020 84
Signal Handling
9/3/2020 85
Thread Pools
9/3/2020 86
Thread Safety
A function is thread-safe if it can be safely invoked by multiple threads at
the same time.
Example of a not safe function:
static int glob = 0;
9/3/2020 88
Thread Specific Data
• Useful when you do not have control over the thread creation
process (i.e., when using a thread pool)
9/3/2020 89
POSIX compliation
On Linux, programs that use the Pthreads API must be compiled with
–pthread. The effects of this option include the following:
_REENTRANT preprocessor macro is defined. This causes the declaration of a few reentrant
functions to be exposed.
http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html
http://codebase.eu/tutorial/posix-threads-c/
9/3/2020 90
Threads vs. Processes
• Advantages of multithreading
o Sharing between threads is easy
o Faster creation
• Disadvantages of multithreading
o Ensure threads-safety
o Bug in one thread can bleed to other threads, since they share the same address
space
o Threads must compete for memory
• Considerations
o Dealing with signals in threads is tricky
o All threads must run the same program
o Sharing of files, users, etc
9/3/2020 92
Operating System Examples
• Windows XP Threads
• Linux Thread
9/3/2020 93
Windows XP Threads
9/3/2020 94
Windows XP Threads
9/3/2020 95
Linux Threads
9/3/2020 96
Linux Threads
9/3/2020 97
References
• Silberschatz A., Galvin P., Gagne G, “Operating Systems Concepts”, VIIIth Edition, Wiley, 2011.
• UKEssays. (November 2018). Compare cpu scheduling of linux and windows. Retrieved from
https://www.ukessays.com/essays/information-systems/compare-cpu-scheduling-of-linux-and-
windows.php?vref=1
9/3/2020 98
THANK YOU
9/3/2020 Silberschatz A., Galvin P., Gagne G, “Operating Systems Concepts”, VIIIth Edition, Wiley, 2011. 99