Inter-process Communication
1
                       IPC
• One process, sometimes, require the output of other
  process
• Therefore, there is a need of well structured
  communication among processes.
• Not preferring interrupts to draw attention.
                                                    2
                           IPC
• Three issues in IPC-
1. How one process can pass information to another
2. Making sure that two or more processes do not get into
   each other’s way when engaging in critical activities
   (both wants last 1 MB space of virtual memory)
3. Proper sequencing when dependency is present (if A
   produces data that B prints, then B cannot print unless A
   is producing some data)
                                                           3
      Inter-thread Communication
•   In case of ITC, the same issues are concerns.
•   The first one is not a headache as threads share some
    common resources and address space; so, they can easily
    communicate.
•   But the other twos are issues in ITC as well.
                                                          4
                 Race Condition
• A process wants to print a file.
• It enters the file name in a special printer directory
• The Printer Daemon periodically checks to see if there is
  any file to print
• If any file is there the Printer Daemon prints them and
  removes their names from the directory
                                                              5
                  Race Condition
• Imagine our directory has a very large number of slots
  (numbered 0,1,2,…) and each one can hold a file name
• There are two shared variables- out that points to the next
  file to be printed and in that points to the next free slot in
  the directory
                                                                   6
Race Condition
                 7
                   Race Condition
• A reads in and stores the
  values 7 to its local variable
• Then a context switch from A
  to B occurs
• B also reads in and stores the
  value 7 to its local variable
• B continues to run and it
  stores the name of its file in
  slot 7 and updates in to 8.
• Then it goes off and does
  other things
                                    8
                    Race Condition
• A runs again starting from
  the place it left off
• It looks its local variable and
  finds 7 there and writes the
  file name in slot 7
• Then A sets in to 8
• As everything went fine, the
  printer daemon will not raise
  any error
                                     9
                 Race Condition
• Process B never gets the chance
• Situations like this where two or more processes are
  reading or writing some shared data and the final result
  depends on who ran precisely are called race
 conditions
                                                             10
                    Critical Regions
• How can we avoid race conditions?
• One way to avoid that is prohibiting more than one
  process from reading and writing the shared data at the
  same time
• This is called   Mutual Exclusion
                                                            11
                Critical Regions
• On the other hand, let’s think in abstract way.
• A process is busy doing internal computations and other
  things that do not lead race conditions
• And sometimes it is busy to access shared memory and
  files or in doing other critical things that lead race
  conditions
• The part of the program where shared memory or
  resources are accesses is called Critical Regions
                                                            12
                  Critical Regions
• We need four conditions to hold for a good
  solution with mutual exclusion-
1.   No two processes simultaneously in critical region
2.   No assumptions made about speeds or numbers of CPUs
3.   No process running outside its critical region may block
     another process
4.   No process must wait forever to enter its critical region
                                                             13
Mutual Exclusion with Critical
          Regions
                                 14
    How can we achieve mutual
           exclusion?
• Now, let’s examine various proposals to achieve mutual
  exclusion
• While one process is busy to update shared memory in its
  critical region, no other process will enter its critical
  region and cause trouble
                                                              15
              Disabling Interrupts
• When a process enters into its critical region, it disables all
  interrupts
• While leaving its critical region, it re-enables all interrupts
• Unattractive and unwise to give user processes the power
  of turning off interrupts. What if one of them did it and
  never turned them on again!! 
• That is the end of the system!!! 
• It is often useful technique within the OS itself but not
  suitable as a general mutual exclusion mechanism
                                                                16
                    Lock Variables
• It’s a software solution
• When a process wants to enter into the critical region, it
  checks the lock variable
• If it is 0, the process sets it to 1 and enters into its critical
  region
• If it is 1, the process waits
                                                                      17
                  Lock Variables
• One process reads the lock and sees 0
• Before it sets 1, another process is scheduled, runs and sets
  the lock 1
• When the first process runs, it will also set the lock 1
• Two processes will be in their critical regions in the same
  time.
                                                              18
                 Strict Alternation
• turn is a variable initially 0 keeps track of whose turn it is to
  enter critical regions
• Process 0 inspects turn and finds 0 and enters into its critical
  region
• Process 1 finds turn to be 0 and continuously tests the value of
  turn
Continuously testing a variable until some value appears is called
Busy Waiting
                                                                      19
             Strict Alternation
• It should usually be avoided as it wastes CPU
  time
• Can be useful when short busy waiting is
  probable
• Requires strict alternating process to provide
  better result
• Inefficient when one process is much slower
  than the other
                                                   20
Peterson’s Solution
                      21
              Common Problem
So far, the techniques we learnt (except disabling
    interrupts)-
1. Lock variables
2. Strict Alternation
3. Peterson’s Solution
•   To achieve mutual exclusion, all have a common
    problem- Busy Waiting
•   In case of prioritized scheduling, low prioritized
    processes will never be fed if Busy Waiting takes place
                                                              22
   Different Mechanisms with
         Sleep and Wake
• Now, we will see more mechanisms to achieve mutual
  exclusion
• These techniques will use Sleep and Wake- two
  system calls
• Sleep causes a process to be suspended until another
  process wakes it up
• Wake causes a process to wake up
                                                         23
     The Producer-Consumer
            Problem
• When the producer sees a full buffer and goes to
  sleep. When the consumer takes out an item, it
  awakes the producer
• When the consumer sees an empty buffer and goes to
  sleep. When the producer puts an item, it awakes the
  consumer
                                                         24
      The Producer-Consumer
             Problem
• We will use count as a variable to stop race conditions
• If the maximum no of information the buffer stores in
  N, then producer first checks if count = N. If yes, then
  it sleeps; otherwise it will add an item and increment
  count by 1
• The consumer tests count. If count = 0, then it sleeps;
  otherwise it removes an information and decrements
  count by 1
                                                             25
The Producer-Consumer
       Problem
                        26
      The Producer-Consumer
             Problem
• Two processes share a common, fixed-sized buffer
• The producer puts information into the buffer
• The consumer takes it out
Problem arises when-
1. Producer wants to put information into a buffer that
   is full
2. Consumer wants to get information from a buffer
   that is empty
                                                          27
      The Producer-Consumer
             Problem
• The buffer is empty; the consumer is about to read
  count = 0
• Scheduler decides at that very instant to stop
  consumer and start producer
• The producer inserts an item and increases count by 1
• The producer will wake the consumer up
• The consumer was not logically sleeping. So, wake
  signal is lost.
• The consumer, on its next run, sees count = 0 and
  sleeps
                                                          28
       The Producer-Consumer
              Problem
• Soon, the producer fills up the buffer and also goes to sleep
Both will sleep forever
• The main problem here is the lost wake up signal.
• If it were not lost, everything would have worked
• To solve this problem, we can use wake up waiting bit
• When a wake up is sent to a process (producer or
    consumer) that is not sleeping, this bit will be set.
• When the sender goes to sleep, it checks this bit
If it is on, then the process will not sleep itself (because
someone MAYBE sleeping)
                                                                  29
                 Semaphores
• It is simply a variable that holds the number of
  wakeups saved for future use
• It is 0 indicating that no wakeups are saved
• It is a positive value indicating number of wakeups
  saved
                                                        30
                  Semaphores
There are 2 operations on semaphores-
• Down- checks if value of semaphore is greater than 0.
    if yes, it decrements the value and continues. If no,
    then it is put to sleep.
• Up- increments its value by 1. If there were sleeping
    processes, any one of them randomly is awakened.
It is guaranteed that if one semaphore operation is
started, no other process can access it. They will have
their chance after operating process is completed/
blocked
                                                            31
Producer-Consumer Problem
     with Semaphores
                            32
 Producer-Consumer Problem with
           Semaphores
• With each semaphore there is an associated waiting queue
• Each entry in a waiting queue has two data items:
   – value (of type integer)
   – pointer to next record in the list
• Two operations:
   – block – place the process invoking the operation on the
     appropriate waiting queue
   – wakeup – remove one of processes in the waiting queue and
     place it in the ready queue
typedef struct{
   int value;
   struct process *list;
   } semaphore;
                                                                 33
Producer-Consumer Problem with
          Semaphores
  wait(semaphore *S) {
     S->value--;
     if (S->value < 0) {
        add this process to S->list;
        block();
     }
  }
  signal(semaphore *S) {
     S->value++;
     if (S->value <= 0) {
        remove a process P from S->list;
        wakeup(P);
     }
  }
                                           34
Producer-Consumer Problem with
          Semaphores
 • n buffers, each can hold one item
 • Semaphore mutex initialized to the value 1
 • Semaphore full initialized to the value 0
 • Semaphore empty initialized to the value n
                                                35
Producer-Consumer Problem with
          Semaphores
The structure of the producer process
      do {
           ...
           /* produce an item in next_produced */
           ...
         wait(empty);
         wait(mutex);
            ...
           /* add next produced to the buffer */
            ...
         signal(mutex);
         signal(full);
      } while (true);
                                                    36
Producer-Consumer Problem with
          Semaphores
 The structure of the consumer process
       Do {
          wait(full);
          wait(mutex);
             ...
         /* remove an item from buffer to next_consumed */
             ...
          signal(mutex);
          signal(empty);
             ...
          /* consume the item in next consumed */
             ...
       } while (true);
                                                       37
38
                      Barriers
Some applications are divided into phases
• And have the rule that no process may proceed to the
  next phase until all processes are ready to proceed to
  the next phase.
• This behaviour maybe achieved by placing a Barrier at
  the end of each phase.
When a process reaches the barrier, it is blocked until all
processes reach the barrier.
                                                              39
Barriers
Barriers
           40
Classical IPC Problems
                         41
      Dining Philosopher Problem
• Five Philosophers seated
  around the circular table
• Each has a plate of Spaghetti
• Each needs two forks to eat
  it
• Between each pair of plates
  there is one fork
                                   42
      Dining Philosopher Problem
• The lives of the philosophers
  consist of two things- eat
  and think
• When a philosopher is
  hungry, he tries to acquire
  his left/ right fork, one at a
  time, in either order
• He only eats after successful
  acquisition of the forks
• He eats for a while and then
  puts them back to think
                                   43
      Dining Philosopher Problem
Is it possible to have a solution
so that no philosophers will be
annoyed? (when his turn is
eating, he eats; when his turn is
thinking, he thinks)
                                    44
                         Solutions
• Philosopher will wait until
   its desired fork is available
• He will grab it when it’s
   available
• What if all the five
   philosophers take their left
   forks simultaneously?
None will be able to take their
right forks; there will be
deadlock
                                     45
                         Solutions
• After taking the left fork,
   philosopher will check if its
   right fork is available
• If it’s not, philosopher puts
   back his left fork, wait for
   some times and proceeds
   again in similar way
• What if all philosophers
   start simultaneously?
They will never find their right
fork available causing
starvation
                                     46
                        Solutions
• Using random start timer
  can solve this problem, but
  not ultimately
• Ethernet LAN works in this
  way, and this happens to be
  finer solution, but again, not
  the best; there is always a
  chance to have a failure
                                    47
                        Solutions
• Well, there is a solution that
  will stop deadlock and
  starvation
• When philosopher wants to
  acquire a fork, she downs
  mutex; when she releases,
  she ups mutex
• The only drawback is only 1
  of 5 philosophers can eat at a
  time though there is a best
  chance of 2 philosophers
  eating at same time
                                    48
                        Solutions
• Our last solution will be
  deadlock free and achieve
  maximum parallelism.
• A philosopher will have 3
  states- eating, thinking, or
  hungry (trying to acquire
  forks)
• A philosopher will move to
  eating state only if none of
  the neighbours is eating
• Only need is that each
  philosopher will have
  individual semaphores
                                    49
  The Readers-Writers Problem
• Dining philosopher problem defines the situation
  where processes compete for limited resources
• The Readers-Writers problem defines the situation
  where database access is required.
• A reader reads… the writer writes… but the reader is
  away and with an old value from the database: simply,
  this is the readers-writers problem
                                                          50
                   Solutions
• When a reader comes along, it UPs a semaphore-
  means, hey, we are reading, do not disturb
• If a writer comes, then it has to wait.
• If more readers come, they are allowed
                                                   51
                     Solution
• When an active reader is reading, then a writer
  comes.
• It sees that a reader is reading, the writer then waits
• If more reader comes, they are queued
• When the active reader finishes, the writer takes place
  its schedule
• After finishing of writer, the queued readers are given
  chances.
• Concurrency problem and lower performance is key
  issue here
                                                            52
    The Sleeping Barber Problem
• In a barber shop, there is one
  barber, some chairs and some
  customers
• A barber sleeps if there is no
  customer (not even on chairs,
  waiting for a haircut )
• A customer wakes up the
  barber if it’s his turn to get
  his haircut
• A customer waits if there is
  any chair left
• A customer leaves, if all the
  chairs are occupied              53
Solution
           54
               Reference
Modern Operating Systems (2nd Edition)
        by Andrew S. Tanenbaum
                                         55