Interprocess Communication
Given 2 processes running concurrently
Example:
//position 1
if( head == NULL)
{
//position 2
head = elem;
//position 3
tail = elem;
}
//position 4
else
{
tail -> next = elem;
tail = elem;
}
A process may be preempted by another process that uses the same memory
location of head.
if preempted time is happened at positions 1 or 4 (see above), there is
no trouble.
if preempted time is happened at positions 2 or 3 (see above), there is
a race condition.
Race condition
A situation where two or more processes
are reading or writing some shared data and the final result depends on
the exact ordering of events.
Critical Section
the part of the program where the shared memory
is accessed.
Q: How do we avoid race condition?
mutual exclusion:
If one process is using a shared variable or file,
the other processes will be excluded from using the same resources.
(i.e. No two processes are ever in their critical
section at the same time.)
Can we get lock before get into critical section and after leave
critical section, we release lock?
Is there any trouble if we use a flag to lock?
while (lock == 1) ; // Do nothing, just
wait
//position 1
lock = 1;
.....
..... // Critical
Section
.....
lock = 0;
If it is interrupted at position 1, the same trouble occurs.
The process was waiting until lock
== 0. Before it announces its turn (i.e. set lock
= 1;), the other process interrupts it and sees that lock is 0.
It runs into critical section. When the CPU time comes back to
the previous process, the latter process is still in critical section and
unable to lock it
since the previous process was on the stage of changing lock and has
not done yet. The previous one will go ahead to get into critical
section.
Now, two processes are in the critical section at the same time period.
Techniques for mutual exclusion: