Chapter4 - Processes(1)

Download Report

Transcript Chapter4 - Processes(1)

Processes and Threads
What is a Process?
 Process – a program in
execution.
 Related terms: Job, Step, Load
Module, Task.
 Process execution must progress
in sequential fashion.
 A process is more than a
program code - It includes 3
segments:
 Program: code/text.
 Data: program variables.
 Stack: for procedure calls and
parameter passing.
Algorithms, Programs, and Processes
Process States
A process state describes the nature of the current activity of a process
A state transition for a process is a change in its state
Process Transitions
 Null New: A new process is created to execute a program.
This event occurs for any of the following reasons:
 An interactive logon to the system by a user
 Created by OS to provide a service on behalf of a user program
 Spawn by existing program
 The OS is prepared to take on a new batch job
Process Transitions
 New  Ready: The OS moves a
new process to a ready state
when it is prepared to take on
additional process (Most
systems set some limit on the
number of existing processes)
 Ready  Running: OS chooses
one of the processes in the ready
state and assigns CPU to it.
 Running  Terminated: The
process is terminated by the OS
if it has completed or aborted.
Process Transitions
 Running  Ready: The
most common reason for
this transition are:
 The running process has
expired his time slot.
 The running process
gets interrupted
because a higher
priority process is in the
ready state.
Process Transitions
 Running  Waiting (Blocked):
A process is put to this state if it
requests for some thing for
which it must wait:
 Process requests for an I/O




operation
Process requests for a resources
Process wishes to wait for a
specified interval of time
Process waits for a message from
another process
Process waits for some action by
another process
Process Transitions
 Waiting  Ready: A process
from a waiting state is moved to
a ready state when the event for
which it has been waiting
occurs.
 Ready  terminated: Not shown
on the diagram. In some
systems, a parent may terminate
a child process at any time. Also,
when a parent terminates, all
child processes are terminated.
 Blocked  terminated: Not
shown. This transition occurs for
the reasons given above.
Suspended Processes
A kernel needs additional states to describe processes suspended due to swapping
UNIX Process States
UNIX Process States
State Transition
 animation
Process Control Block (PCB)
Struct PCB {
unsigned
unsigned
umsigned
State
Regs
unsigned
:
};
int PID;
int UID;
int PPID;
pstate;
context;
int priority;
Process Table
Process Scheduling Queues
Example of a Ready Queue and
Device Queues
Schedulers
 A process may migrate between the various queues.
 The OS must select, for scheduling purposes,
processes from these queues.
Different Schedulers
Long-term scheduler (or job scheduler) – selects which
processes should be brought into the ready queue. Controls
degree of multiprogramming.
Short-term scheduler (or CPU scheduler) – selects which
process should be executed next and allocates CPU. Shortterm scheduler is invoked very frequently (milliseconds)
Medium term scheduler: - determines which processes are to
be suspended and resumed
Multiprogramming Revisited
Combined trace of processes
Process Context
 Each time a process is removed from access to the processor, sufficient
information on its current operating state must be stored (in the PCB)
of the process)such that when it is again scheduled to run on the
processor it can resume its operation from an identical position.
 This operational state data is known as its context.
Process Switch
 A process switch may
occur whenever the OS
has gained control of
CPU. i.e., when:
 Supervisor Call
 Trap
 Interrupt
Context Switching
 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 this is called context switch.
 The time it takes is
dependent on hardware
support.
 Context-switch time is
overhead; the system does no
useful work while switching.
Steps in Context Switching
 Save context of processor including program counter
and other registers.
 Update the PCB of the running process with its new
state and other associate information.
 Move PCB to appropriate queue - ready, blocked,
 Select another process for execution.
 Update PCB of the selected process.
 Restore CPU context from that of the selected process.
Process Creation
 When the OS or a user process decides to create a new
process, it can proceed as follows:
 Assign a new process identifier and add its entry to the primary




process table.
Allocate space for the process (program+data) and user stack. The
amount of space required can set to default values depending on the
process type. If a user process spawns a new process, the parent
process can pass these values to the OS.
Create process control block.
Set appropriate linkage to a queue (ready) is set.
Create other necessary data structures (e.g. to store accounting
information).
Linux Example
#include <stdio.h>
#include <stdio.h>
int main()
{
int f;
cout << “Hello\n”;
f=fork();
cout << “Hello\n”;
return 0;
}
void main()
{
int f;
cout << “Hello\n”;
f=fork();
cout << “Hello\n”;
return 0;
}
Example 2
#include <stdio.h>
void ChildProcess();
void main()
{
int pid, cid, r;
pid = getpid();
r = fork(); //create a new process
if (r == 0) //r=0 -> it’s child
{
cid = getpid(); //get process ID
printf("I am the child with cid = %d of pid =
%d \n", cid, pid);
ChildProcess();
exit(0);
}
else
{
printf("Parent waiting for the child...\n");
wait(NULL);
printf("Child finished, parent quitting
too!");
}
}
void ChildProcess()
{
int i;
for (i = 0; i < 5; i++)
{
printf(“%d ..\n", i);
sleep(1);
}
}
Parent
#include
#define NULL
<sys/wait.h>
0
int main (void)
{
if (fork() == 0){ /*This is the child process */
execve("child",NULL,NULL);
exit(0);/*Should never get here, terminate */
}
/* Parent code here */
printf("Process[%d]: Parent in execution ...\n",
getpid());
sleep(2);
if(wait(NULL) > 0) /* Child terminating */
printf("Process[%d]: Parent detects
terminating child \n",getpid());
printf("Process[%d]: Parent terminating ...\n",
getpid());
}
int main (void)
{
/* The child process's new program
This program replaces the parent's program */
printf("Process[%d]: child in execution ...\n",
getpid());
sleep(1);
printf("Process[%d]: child terminating ...\n",
getpid());
}
Cooperating Processes
 The concurrent processes executing in the OS may be
either independent or cooperating.
 Independent process cannot affect or be affected by the
execution of another process. It does not share data
with any other process.
 Cooperating process can affect or be affected by the
execution of another process. It shares data with other
process(es).
Threads
 A thread, also called a
lightweight process (LWP), is
the basic unit of CPU
utilization.
 It has its own program
counter, a register set, and
stack space.
 It shares with the pear
threads its code section, data
section, and OS resources
such as open files and signals,
collectively called a task.
Threads
A word processor with three threads
A multithreaded Web server
(a) Dispatcher thread (b) Worker thread
User-Level and Kernel-Level Threads
 There are two types of threads: user-level and kernel-level.
 User-level thread avoids the kernel and manages the tables itself.
 These threads are implemented in user-level libraries rather than via




system calls.
Often this is called "cooperative multitasking" where the task defines a set
of routines that get "switched to" by manipulating the stack pointer.
Typically each thread "gives-up" the CPU by calling an explicit switch,
sending a signal or doing an operation that involves the switcher. Also, a
timer signal can force switches.
User threads typically can switch faster than kernel threads.
Three primary thread libraries:
 POSIX Pthreads
 Win32 threads
 Java threads
POSIX Threads
 The ANSI/IEEE Portable Operating System Interface (POSIX) standard
defines pthreads API
 For use by C language programs
 Provides 60 routines that perform the following:
Thread management
 Assistance for data sharing─mutual exclusion
 Assistance for synchronization─condition variables
 A pthread is created through the call


pthread_create(< data structure >,< attributes >,
< start routine >,< arguments >)
 Parent-child synchronization is through pthread_join
 A thread terminates pthread_exit call