Beruflich Dokumente
Kultur Dokumente
10.1 BASICS OF OS
OS acts as a bridge b/w user applications and task and the underlying
system resources
Primary functions of an OS are:
Make the system convenient to use
Organize and manage the system resources efficiently and correctly
Operating system
architecture
Protection systems:
Multiple users with different level of access permissions
Implementing security policies
Interrupt handler
Configurability
Services in Server can be restarted without need to restart the whole system
Task/Process Management
Task/Process scheduling
Task/Process synchronization
Error/Exception handling
Memory management
Interrupt handling
Time management
Task/Process Management
TCB contains:
1. Task ID
2. Task State
3. Task Type
4. Task Priority
5. Task Context Pointer
6. Task Memory Pointers
7. Task System Resource Pointers
8. Task Pointers
Task/Process Scheduling
Task/Process Synchronization
Error/Exception Handling
Errors occurred during execution of tasks
Insufficient memory, timeouts, deadlocks, deadline missing, bus error, divide by
zero, etc
Kernel level exception Deadlock
Task level exception Timeout
API GetLastError() Windows CE RTOS
Memory Management
Interrupt Handling :
Created state
Ready state
Running state
Blocked state
Completed state
State Transition
READY
PEND (BLOCKED)
DELAY(process is sleeping)
SUSPEND
MicroC/OS-II
DORMANT (CREATED)
READY
RUNNING
WAITING
INTERRUPTED
THREADS
Primitive that can execute code
Single sequential flow of control within a process
Light weight process
Memory organization of a process and its threads
MULTITHREADING
Better memory utilization
Speeds up execution
of process
CPU utilization
THREAD STANDARDS
POSIX Threads:
Portable Operating System Interface
Library Pthreads (creation and management functions in C)
int pthread_create(pthread_t *new_thread_ID,
const pthread_attr_t *attribute,
void * (*start_function) (void *),
void *arguments);
int pthread_join(pthread_t new_thread, void * *thread_status);
Return value of 0 success
Example 1
#include<pthread.h>
#include<stdlib.h>
#include<stdio.h>
void *new_thread(void *thread_args)
{
int i, j;
for(j=0; j<5; j++)
{
printf(Hello I am the new thread\n);
for(i=0; i<10000; i++) ;
}
return NULL;
}
//sleep(), delay()
Example 1(contd)
int main(void)
{
int i,j;
pthread_t tcb;
if (pthread_create ( &tcb, NULL, new_ thread, NULL))
{
printf(Error in creating new thread\n);
return -1;
}
for(j=0; j<5; j++)
{
printf(hello an in main thread\n);
for(i=0; i<10000; i++);
}
Example 1(contd)
if (pthread_join (tcb, NULL ) )
{
printf(Error in thread join\n);
return -1;
}
return -1;
}
Example 1(contd)
Thread Termination :
1.
Natural termination (return or pthread_exit())
2.
Forced termination ( pthread_cancel() )
Win 32 Threads
Win 32 Threads
GetCurrentThread(void)
GetCurrentThreadId(void)
GetThreadPriority(void)
SetThreadPriority(HANDLE hThread, int n Priority)
Example
#include<windows.h>
#include<stdio.h>
//Child Thread
void ChildThread(void)
{
char i;
for (i=0; i<=10; ++i)
{
printf(Executing Child Thread: Counter = %d\n, i);
Sleep(500);
}
}
Example(contd)
//Primary Thread
int main(int argc, char* argv[])
{
HANDLE hThread;
DWORD dwThreadID;
char i;
hThread= CreateThread(NULL, 1000, (LPTHREAD_START_ROUTINE)
ChildThread, NULL, 0, &dwthreadID);
if(hThread==NULL)
{
printf(Thread creation failed\n Error no:%d\n, GetLastError());
return 1;
}
Example(contd)
//Primary Thread
for(i=0; i<=10;i++)
{
printf(Executing main thread: Counter=%d\n,i);
Sleep(500);
}
return 0;
}
Java Threads
import java.lang.*;
public class MyThread extends Thread
{
public void run()
{
System.out.println(Hello from mythread\n);
}
public static void main(Srring args[])
{
(new MyThread()).start(); //waiting for execution
}
}
Java Threads
MyThread.start()
Ready state
MyThread.yield()
Voluntarily gives up execution of thread
Ready state
MyThread.sleep(100)
Forces to sleep for the duration mentioned
Suspend mode and again back Ready state
Thread pre-emption
Many-to-One Model
1.
Solaris Green Threads
2.
GNU Portable Thread
One-to-One Model
1.
Windows XP/NT/2000
2.
Linux Threads
Many-to-Many Model
1.
Windows NT/2000
2.
ThreadFibre
CONTEXT SWITCHING :
Saving current context details for currently running process at the CPU
Switching
CONTEXT RETRIEVAL:
Types of Multitasking
CO-OPERATIVE MULTITASKING:
Task Scheduling
Ready
Priority based
pre-emptive
Blocked/Waiting
Ready
Pre-emptive /
non pre-emptive
Running
Running
Blocked/Waiting
Pre-emptive /
non pre-emptive /
cooperative
Completed
It should be high
It should be high
TURNAROUND TIME:
Time waiting for memory + time in ready queue + time spend for I/O + time
spent for execution
It should be minimal
RESPONSE TIME:
It should be least
Various QUEUES in OS
JOB QUEUE:
Allocate CPU based on the order in which they enter Ready queue
Ticketing Reservation system
Example 1
Three Process with IDs P1,P2,P3 with estimated completion time 10,5,7 milliseconds
respectively enters ready queue in the order P1, P2, P3. Calculate waiting time
and turn around time for each process and also average waiting time and turn
around time(Assume no I/O waiting for the processes)
Example 2
Calculate waiting time and turn around time for each process and also average waiting
time and turn around time(Assume no I/O waiting for the processes) for the
above example if process enters the Ready Queue in the order P2, P1, P3
Starvation
Cannot predict next shortest process in the Ready queue for scheduling
Preemptive Scheduling
Preemptive SJF Scheduling/ Shortest Remaining Time(SRT)
Example 1
Three Process with IDs P1,P2,P3 with estimated completion time 10,5,7 milliseconds
respectively enters ready queue together. A new process P4 enters with
estimated completion time 2ms enters the Ready queue after 2ms. calculate the
waiting time and turn around time for each process and also average waiting
time and turn around time.
Preemptive Scheduling
Round Robin (RR) Scheduling
Preemptive Scheduling
Round Robin (RR) Scheduling
Example 1
Three Process with IDs P1,P2,P3 with estimated completion time 6,4,2
milliseconds respectively enters ready queue together IN THE
ORDER P1,P2,P3. calculate the waiting time and turn around time
for each process and also average waiting time and turn around
time using RR algorithm with Time slice =2ms.
Preemptive Scheduling
Priority Based Scheduling
Example 1
Three Process with IDs P1,P2,P3 with estimated completion time 10,5,7
milliseconds and priorities 1,3,2 (0 highest priority and 3 lowest
priority) respectively enters ready queue together. A new process
P4 with estimated completion time 6ms and priority 0 enters the
Ready Queue after 5ms of execution of P1. calculate the waiting
time and turn around time for each process and also average
waiting time and turn around time.
Process 1
void main(void)
{
DWORD id;
HANDLE hThread;
// Create thread with normal priority
hThread=CreateThread(NULL,0,
(LPTHREAD_START_ROUTINE)Task,
(LPVOID) 0, 0, &id);
if(NULL==hThread)
{
printf(Creating thread Failed: Error code= %d, GetLastError());
return;
}
WaitForSingleObject(hThread, INFINITE);
return;
}
Process 2
void main(void)
{
DWORD id;
HANDLE hThread;
// Create thread with above normal priority
hThread=CreateThread(NULL,0,
(LPTHREAD_START_ROUTINE)Task,(LPVOID)0,
CREATE_SUSPENDED, &id);
if(NULL==hThread)
{
printf(Creating thread Failed: Error code= %d, GetLastError());
return;
}
Process 2
SetThreadPriority(hThread,
THREAD_PRIORITY_ABOVE_NORMAL);
ResumeThread(hThread);
WaitForSingleObject(hThread, INFINITE);
return;
}
IDLE PROCESS(TASK)
void Idle_Process (void)
{
//simple wait doing nothing
While(1);
}
Task Communication
Based on the degree of interaction:
1.
Co-operating processes
2.
Competing processes
Cooperation through sharing(through some shared resources)
Cooperation through communication(communicate for synchronization)
Shared Memory:
Task Communication
Implementing Shared Memory:
1.
Pipes:
Client-server architecture
Pipe server and pipe client
Unidirectional and bidirectional
Message Passing
1.
Message queue
FIFO
send(Name of the process to which message is to be sent, message)
receive(Name of the process from which message is be sent,
message)
Synchronous
Message Passing
Message queue
PostMessage(HWND hWnd, UINT Msg, WPARAM wParam,
LPARAM lParam)
PostThreadMessage(DWORD idThread, UINT Msg, WPARAM
wParam, LPARAM lParam)
SendMessage(HWND hWnd, UINT Msg, WPARAM wParam,
LPARAM lParam)
CreateMsgQueue(LPCWSTR lpszName, LPMSGQUEUEOPTIONS
lpOptions)
Message Passing
typedef MSGQUEUEOPTIONS_OS{
DWORD dwSize;
DWORD dwFlags;
DWORD dwMaxMessages;
DWORD cbMaxMessages;
BOOL bReadAccess;
};
Message Passing
Message queue
OpenMsgQueue()
dwFlags==MSGQUEUE_MSGALERT
MailBox
Signalling
os_send_signal
os_wait
Stream Socket
Datagram Socket
Task Synchronization
1.
2.
3.
4.
5.
6.
1. Racing
#include<windows.h>
#include<stdio.h>
char Buffer[10]={1,2,3,4,5,6,7,8,9,10};
short int counter=0;
void Process_A(void) {
int i;
for(i=0; i<5; i++) {
if(Buffer[i] >0)
counter++;
}
}
1. Racing
void Process_B(void) {
int j;
for(j=0; j<5; j++) {
if(Buffer[j] >0)
counter++;
}
}
1. Racing
int main()
{
DWORD id;
CreateThread(NULL,0,
(LPTHREAD_START_ROUTINE)Process_A,(LPVOID) 0, 0, &id);
CreateThread(NULL,0,
(LPTHREAD_START_ROUTINE)Process_B,(LPVOID) 0, 0, &id);
Sleep(100000);
return 0;
}
1. Racing
mov eax , dword ptr [ebp-4];
add eax,1;
mov dword ptr [ebp-4] , eax;
1. Racing
2. Deadlock
Mutual Exclusion
No Resource Preemption
Circular Wait
Deadlock Handling
Ignore Deadlocks :
Ex: UNIX
Detect and Recover Deadlocks :
Deadlock Handling
Avoid Deadlocks :
Mutual Exclusion
No Resource Preemption
Deadlock Handling
Five philosophers ( n )
Eating , Hungry or Brainstorming
Only 5 forks ( need 2)
Circular chain
Round Robin
Imposing rules in accessing the forks by philosophers
Philosopher acquires a semaphore ( mutex) before picking up ant fork
Buffer overrun
Buffer under-run
SOLUTIONS:
1.
5. Readers-Writers Problem
6. Priority Inversion
High priority task waiting for low priority task to release a resource and
a medium priority task continue execution by preempting low priority
task
Binary semaphore
0 locked
1 unlocked
Priority Inheritance
Priority Ceiling
Mutual exclusion
CPU is busy checking the lock to see whether they can proceed
Not feasible in embedded systems(power consumption)
Sleep & Wake up mechanisms
Process in critical section new process accessing critical section will
goto Sleep process owning critical section wakeup the new process
when it lives the critical section
1. Semaphore :
Binary Semaphore(mutex)
InitializeCriticalSection(LPCRITICAL_SECTION lpCriticalSection)
EnterCriticalSection(LPCRITICAL_SECTION lpCriticalSection)
Wait queue
TryEnterCriticalSection(LPCRITICAL_SECTION lpCriticalSection)
LeaveCriticalSection(LPCRITICAL_SECTION lpCriticalSection)
DeleteEnterCriticalSection(LPCRITICAL_SECTION lpCriticalSection)
DEVICE DRIVERS
DEVICE DRIVERS
Processor support
Real-Time Capabilities
Modularization support
Cost
Ease of use