9-Operating Systems -Synchronization, interprocess communication, deadlock(1)
9-Operating Systems -Synchronization, interprocess communication, deadlock(1)
Communication
Synchronization,
Deadlocks
Dr. M. Brindha
Associate Professor
Department of CSE
NIT, Trichy-15
Inter Process
Communication
• Advantages of Inter Process Communication (IPC)
– Information sharing
– Modularity/Convenience
• 3 ways
– Shared memory
– Message Passing
– Signals
Shared
Memory userspace
• One process will create an area in RAM which
the other process can access Process 1
• Both processes can access shared memory like
a regular working memory
– Reading/writing is like regular reading/writing
– Fast Shared
• Limitation : Error prone. Needs synchronization memory
between processes
Process 2
Shared Memory in
Linux
• int shmget (key, size, flags)
– Create a shared memory segment;
– Returns ID of segment : shmid
– key : unique identifier of the shared memory segment
– size : size of the shared memory (rounded up to the
PAGE_SIZE)
• int shmat(shmid, addr, flags)
– Attach shmid shared memory to address space of the
calling process
– addr : pointer to the shared memory address space
• int shmdt(shmid)
– Detach shared memory
Example
server. client.c
c
Message
Passing userspace
• Shared memory created in the kernel
Process 1
• System calls such as send and receive
used for communication
– Cooperating : each send must have a
receive
•
Advantage : Explicit sharing, less error Process 2
prone
•
Limitation : Slow. Each call involves
marshalling / demarshalling of Kernel
information
Shared
memory
Pipe
s
– Always between parent and child
– Always unidirectional
– Accessed by two associated file descriptors:
• fd[0] for reading from pipe
• fd[1] for writing to the pipe
Pipes for two
way
communicatio
n
ref : http://www.comptechdoc.org/os/linux/programming/linux_pgsignals.html 10
Synchronization
Motivating
Scenario
shared variable
program 0 int counter=5; program 1
{ {
* *
* *
counter++ counter--
* *
} }
• Single core
– Program 1 and program 2 are executing at the same time but sharing a
single core
1 2 1 2 1 2 1 2
{
*
*
counter++ critical section
*
} No more than one
process should execute in
critical section at a time
Race Conditions in
Multicoreshared variable
program 0 int counter=5; program 1
{ {
* *
* *
counter++ counter--
* *
} }
• Multi core
– Program 1 and program 2 are executing at the same time on different
cores
1
2
CPU usage wrt time
Critical
Section
• Requirements
– Mutual Exclusion : No more than one process in
critical section at a given time
– Progress : When no process is in the critical section,
any process that requests entry into the critical
section must be permitted without any delay
– No starvation (bounded wait): There is an upper
bound on the number of times a process enters the
critical section, while another is waiting.
Locks and
Unlocks
shared variable
program 0 int counter=5; program 1
{ lock_t L; {
* *
* *
lock(L) lock(L)
counter++ counter--
unlock(L)
* unlock(L)
} *
}
• lock(L) : acquire lock L exclusively
– Only the process with L can access the critical section
• unlock(L) : release exclusive access to lock L
– Permitting other processes to access the critical section
Whento have
Locking?
• Single instructions by themselves are
atomic
eg. add %eax, %ebx
• Simple
– When interrupts are disabled, context switches won’t
happen
• Requires privileges
– User processes generally cannot disable interrupts
• Not suited for multicore systems
Software Solution
(Attempt 1)
Shared
int turn=1;
Process 1 Process 2
while(1){ while(1){
while(turn == 2); // lock while(turn == 1); // lock
critical section critical section
turn = 2; // turn = 1; // unlock
unlock other other code
code }
}
Both p1 and p2 can enter into the critical section at the same time
Software Solution
(Attempt 3)
globally defined
p2_wants_to_enter, p1_wants_to_enter
Process 1 Process 2
while(1){ while(1){
p1_wants_to_enter = True p2_wants_to_enter = True
lock while(p2_wants_to_enter = True); while(p1_wants_to_enter = True);
critical section critical section
k p1_wants_to_enter = False
unloc p2_wants_to_enter = False
other code other code
} }
There is a tie!!!
http://research.microsoft.com/en-us/um/people/lamport/pubs/bakery.pdf 29
Simplified Bakery
Algorithm
• Processes numbered 0 to N-1
• num is an array N integers (initially 0).
– Each entry corresponds to a process
lock(i){ num[i] = MAX(num[0], num[1], ….,
num[N-1]) + 1 for(p = 0; p < N; ++p){
while (num[p] != 0 and num[p] < num[i]);
}
}
critical section
Choosing ensures that a process
unlock(i)
Is not at the doorway
{ num[i] =
0;
}
(a, b) < (c, d) which is equivalent to: (a < c) or ((a == c) and (b < d)) 31
Analyze
this
• Does this scheme provide mutual exclusion?
Process 1 Process 2
while(1) while(1)
{ while(lock != { while(lock !=
0); lock= 1; // 0); lock = 1; //
lock critical lock critical
section section
lock = 0; // lock = 0; // unlock
unlock other other code
code }
} lock = 0
No P1: while(lock != 0); context switch
P2: while(lock != 0);
P2: lock = 1;
P1: lock = 1;
…. Both processes in critical section
If
only…
• We could make this operation atomic
Process 1
while(1){
Make atomic
while(lock != 0);
lock= 1; // lock
critical section
lock = 0; // unlock
other code
}
• Mutex
• Semaphore
Spinlocks
Process 1
Usage
acquire(&locked) int xchg(addr, value){
critical section %eax = value
release(&locked) xchg %eax, (addr)
}
Process 2
acquire(&locked) void acquire(int *locked){
critical section while(1){
release(&locked) if(xchg(locked, 1) == 0)
• One process will acquire the lock break;
}
• The other will wait in a loop }
repeatedly checking if the lock is
available void release(int *locked){
• The lock becomes available when locked = 0;
the former process releases it }
Memory
X
• No caching of (X) possible. All xchg operations are bus
transactions.
– CPU asserts the LOCK, to inform that there is a ‘locked ‘ memory
• access
acquire function in spinlock invokes xchg in a loop…each operation
is a bus transaction …. huge performance hits
int xchg(addr,
value){
A better acquire
%eax = value
xchg %eax, (addr)
}
lock
unlock
create spinlock
destroy spinlock
Mutexe
s int xchg(addr, value){
• Can we do better than busy %eax = value
xchg %eax, (addr)
waiting? }
– If critical section is locked then
yield CPU void lock(int *locked){
• Go to a SLEEP state while(1){
if(xchg(locked, 1) == 0)
– While unlocking, wake up
break;
sleeping process else
sleep();
}
}
46
Locks and
Priorities
• What happens when a high priority task requests
a lock, while a low priority task is in the critical
section
– Priority Inversion
– Possible solution
• Priority Inheritance
Producer Consumer
Producer-Consumer
Code
Buffer of size N
int count=0;
Mutex mutex,
1 void producer(){ empty, full;
1 void consumer(){
2 while(TRUE){ 2 while(TRUE){
3 item = 3 if (count == 0) sleep(full);
4 produce_ite 4 lock(mutex);
5 m(); 5 item = remove_item(); // from buffer
6 if (count == N) sleep(empty); 6 count--;
7 lock(mutex); 7 unlock(mutex);
8 insert_item(item); // into buffer 8 if (count == N-1) wakeup(empty);
9 count++; 9 consume_item(item);
10 unlock(mutex); 10 }
if (count == 1) wakeup(full); }
}
}
Lost
Wakeups
• Consider the following 3 read count value // count 0
3 item = produce_item();
context of 5 lock(mutex);
• instructions 6insert_item(item); // into buffer
7 count++; // count = 1
Assume buffer is initially 8 unlock(mutex)
empty 9 test (count == 1) // yes
context switch 9 signal(full);
3 test (count == 0) // yes
3 wait();
What happens if only philosophers A and C are always given the priority?
B, D, and E starves… so scheme needs to be fair
E
First
Try
#define N 5
5 1
A void philosopher(int i){
D while(TRUE){
think(); // for some_time
take_fork(i);
4 2 take_fork((i + 1) % N);
eat();
put_fork(i); put_fork((i
3 + 1) % N);
C B
}
}
What happens if all philosophers decide to pick up their right forks at the same
time? Possible starvation due to deadlock
Deadlock
s
•
• A situation where programs continue to run
• indefinitely without making any progress
• Each program is waiting for an event that
another process can cause
Second
try
• Take fork i, check if fork (i+1)%N is #define N 5
available
• Imagine, void philosopher(int i){
– All philosophers start at the same time
while(TRUE){
– Run simultaneously
– And think for the same time
think();
take_fork(i);
• This could lead to philosophers taking
fork and putting it down continuously. a if (available((i+1)%N)
deadlock. { take_fork((i + 1) %
N); eat();
• A better alternative }else{
– Philosophers wait a random time before put_fork(i);
take_fork(i) }
– Less likelihood of deadlock.
– Used in schemes such as Ethernet
}
Solution using Mutex
• Protect critical sections with a #define N 5
mutex
void philosopher(int i){
• Prevents deadlock while(TRUE){
• But has performance issues think(); // for some_time
wait(mutex);
– Only one philosopher can eat at a
take_fork(i);
time
take_fork((i + 1) % N);
eat();
put_fork(i); put_fork((i
+ 1) % N);
signal(mutex);
}
}
Solution to Dining
Philosophers
Uses N semaphores (s[0], s[1], …., s[N]) all initialized to 0, and a mutex
Philosopher has 3 states: HUNGRY, EATING, THINKING
A philosopher can only move to EATING state if neither neighbor is
eating
void philosopher(int i){
while(TRUE){ void take_forks(int i) void put_forks(int i){
think(); { lock(mutex); lock(mutex);
take_forks(i); state[i] = HUNGRY; state[i] = THINKING;
eat(); test(i); test(LEFT);
put_forks(); unlock(mutex); test(RIGHT)
} down(s[i]); unlock(mutex);
} } }
A B
olds R2
h
R2 B urce
o
es
r
A B
Aw
res aits
ou
rce for olds R2
R h
2 R2 B urce
o
es
r
A Deadlock Arises:
Deadlock : A set of processes is deadlocked if each process in the set is
waiting for an event that only another process in the set can cause.
Conditions for Resource
Deadlocks
1. Mutual Exclusion
– Each resource is either available or currently assigned to exactly one
process
2. Hold and wait
– A process holding a resource, can request another resource
3. No preemption
– Resources previously granted cannot be forcibly taken away from a
process
4. Circular wait
– There must be a circular chain of two or more processes, each of
which is waiting for a resouce held by the next member of the chain
Deadlock occurs
No dead lock occurrence
(B can be granted S
after step q)
Should Deadlocks be
handled?
• Preventing / detecting deadlocks could be tedious
• Can we live without detecting / preventing deadlocks?
– What is the probability of occurrence?
– What are the consequences of a deadlock? (How critical is a
deadlock?)
Handling
Deadlocks
• Detection and Recovery
• Avoidance
• Prevention
Deadlock
detection
• How can an OS detect when there is a
deadlock?
• OS needs to keep track of
– Current resource allocation
• Which process has which resource
– Current request allocation
• Which process is waiting for which resource
• Use this informaiton to detect
deadlocks
Deadlock
Detection
• Deadlock detection with one resource of each type
• Find cycles in resource graph
Deadlock
Detection
• Deadlock detection with multiple resources of each type
P1
P2
Current Allocation Matrix Request Matrix
P3 Who has what!! Who is waiting for what!!
Process Pi holds Ci resources and requests Ri resources, where i = 1 to 3
Goal is to check if there is any sequence of allocations by which all current
requests can be met. If so, there is no deadlock.
Deadlock
Detection
• Deadlock detection with multiple resources of each type
P1 P1 cannot be satisfied
P2 P2 cannot be satisfied
P3 can be satisfied
P3 Current Allocation Matrix Request Matrix
P1
P2
P3
P1 P1 cannot be satisfied
P2 P2 cannot be satisfied
2 1 1 0
P3 cannot be satisfied
P3 Current Allocation Matrix Request Matrix
deadlock
Process Pi holds Ci resources and requests Ri resources, where i = 1 to
3 Deadlock detected as none of the requests can be satisfied
Deadlock
Recovery
What should the OS do when it detects a deadlock?
• Raise an alarm
– Tell users and administrator
• Preemption
– Take away a resource temporarily (frequently not possible)
• Rollback
– Checkpoint states and then rollback
• Kill low priority process
– Keep killing processes until deadlock is broken
– (or reset the entire system)
Deadlock
Avoidance
• System decides in advance if allocating a resource to a
process will lead to a deadlock Both processes request
process 2 instructions Resource R1
R1 Unsafe state
(may cause a deadlock)
R2 Both processes
request
Resource R2
Deadlock unsafe
safe
3. No preemption
– Pre-empt the resources, such as by virtualization of resources (eg. Printer
spools)
4. Circular wait
– One way, process holding a resource cannot hold a resource and request for
another one
– Ordering requests in a sequential / hierarchical order.
Hierarchical Ordering of
Resources
• Group resources into levels
(i.e. prioritize resources numerically)
• A process may only request resources at higher levels
than any resource it currently holds
• Resource may be released in any order
• eg.
– Semaphore s1, s2, s3 (with priorities in
increasing order) down(S1); down(S2); down(S3) ;
allowed
down(S1); down(S3); down(S2); n o t allowed
Thank You!!!