SlideShare a Scribd company logo
6 Indirect Communication
 • P and V are low level primitives for protecting critical sections and
   establishing synchronization between tasks.
 • Shared variables provide the actual information that is communicated.
 • Both of these can be complicated to use and may be incorrectly placed.
 • Split-binary semaphores and baton passing are complex.
 • Need higher level facilities that perform some of these details
   automatically.
 • Get help from programming-language/compiler.

6.1 Critical Regions
 • Declare which variables are to be shared, as in:
      VAR v : SHARED INTEGER
 • Access to shared variables is restricted to within a REGION statement,
   and within the region, mutual exclusion is guaranteed.
   Except as otherwise noted, the content of this presentation is licensed under the Creative Com-
mons Attribution 2.5 License.
                                              169
170
                                 semaphore v_lock(1);
    REGION v DO                  P(v_lock)
       // critical section           ...    // x = v; (read) v = y (write)
    END REGION                   V(v_lock)
• Nesting can result in deadlock.
    VAR x, y : SHARED INTEGER

    task1                    task2
    REGION x DO                  REGION y DO
       ...                          ...
       REGION y DO                  REGION x DO
           ...                          ...
       END REGION                   END REGION
       ...                          ...
    END REGION                   END REGION
• Simultaneous reads are impossible!
• Modify to allow reading of shared variables outside the critical region
  and modifications in the region.
• Problem: reading partially updated information while a task is updating
171
  the shared variable in the region.

6.2 Conditional Critical Regions
• Introduce a condition that must be true as well as having mutual
  exclusion.
    REGION v DO
       AWAIT conditional-expression
       ...
    END REGION
• E.g. The consumer from the producer-consumer problem.
    VAR Q : SHARED QUEUE<INT,10>

    REGION Q DO
       AWAIT NOT EMPTY( Q ) buffer not empty
       take an item from the front of the queue
    END REGION
  If the condition is false, the region lock is released and entry is started
  again (busy waiting).
172
6.3 Monitor
• A monitor is an abstract data type that combines shared data with
  serialization of its modification.
    _Monitor name {
       shared data
       members that see and modify the data
    };

• A mutex member (short for mutual-exclusion member) is one that does
  NOT begin execution if there is another active mutex member.
  – ⇒ a call to a mutex member may become blocked waiting entry, and
    queues of waiting tasks may form.
  – Public member routines of a monitor are implicitly mutex and other
    kinds of members can be made explicitly mutex ( _Mutex).
• Basically each monitor has a lock which is Ped on entry to a monitor
  member and Ved on exit.
173
    class Mon {
        int v;
         uSemaphore MonitorLock(1)
      public:
        int x(. . .) {
              MonitorLock.P()
              ...         // int temp = v;
              MonitorLock.V()
              return v;   // return temp;
         }

• Unhandled exceptions raised within a monitor always release the
  implicit monitor locks so the monitor can continue to function.
• Atomic counter using a monitor:
174
    _Monitor AtomicCounter {
           int counter;
       public:
           AtomicCounter( int init ) : counter( init ) {}
           int inc() { counter += 1; return counter; }
           int dec() { counter -= 1; return counter; }
    };
    AtomicCounter a, b, c;
    . . . a.inc(); . . .
    . . . b.dec(); . . .
    . . . c.inc(); . . .
• Recursive entry is allowed (owner mutex lock), i.e., one mutex member
  can call another or itself.
• Destructor is mutex, so ending a block with a monitor or deleting a
  dynamically allocated monitor, blocks if thread in monitor.

6.4 Scheduling (Synchronization)
• A monitor may want to schedule tasks in an order different from the
  order in which they arrive.
175
• There are two techniques: external and internal scheduling.
  – external is scheduling tasks outside the monitor and is accomplished
    with the accept statement.
  – internal is scheduling tasks inside the monitor and is accomplished
    using condition variables with signal & wait.

6.4.1 External Scheduling
 • The accept statement controls which mutex members can accept calls.
 • By preventing certain members from accepting calls at different times, it
   is possible to control scheduling of tasks.
 • E.g. Bounded Buffer
176
                                                                           b
_Monitor BoundedBuffer {                                mutex routines         calling
     int front, back, count;                          insert remove        d
     int Elements[20];
                                                        b         d        c
   public:
     BoundedBuffer() : front(0), back(0), count(0) {} c           a        a
     _Nomutex int query() { return count; }
     [_Mutex] void insert( int elem );                       shared data
     [_Mutex] int remove();
};
                                                                                   acceptor
void BoundedBuffer::insert( int elem ) {
     if ( count == 20 ) _Accept( remove ); // hold insert calls  exit
     Elements[back] = elem;
     back = ( back + 1 ) % 20;
     count += 1;
}
int BoundedBuffer::remove() {
     if ( count == 0 ) _ Accept( insert ); // hold remove calls
     int elem = Elements[front];
     front = ( front + 1 ) % 20;
     count -= 1;
     return elem;
}
177
• Queues of tasks form outside the monitor, waiting to be accepted into
  either insert or remove.
• An acceptor blocks until a call to the specified mutex member(s) occurs.
• Accepted call is executed like a conventional member call.
• When the accepted task exits the mutex member (or blocks), the
  acceptor continues.
• If the accepted task does an accept, it blocks, forming a stack of blocked
  acceptors.

6.4.2 Internal Scheduling
 • Scheduling among tasks inside the monitor.
 • A condition is a queue of waiting tasks:
     uCondition x, y, z[5];

• A task waits (blocks) by placing itself on a condition:
     x.wait();    // wait( mutex, condition )
  Atomically places the executing task at the back of the condition queue,
  and allows another task into the monitor by releasing the monitor lock.
178
• A task on a condition queue is made ready by signalling the condition:
    x.signal();
   This removes a blocked task at the front of the condition queue and
  makes it ready.
• Like Ving a semaphore, the signaller does not block, so the signalled
  task must continue waiting until the signaller exits or waits.
• A signal on an empty condition is lost!
179
• E.g. Bounded Buffer (like binary semaphore solution):
 _Monitor BoundedBuffer {
      uCondition NonEmpty, NonFull;
      int front, back, count;
      int Elements[20];
    public:
      BoundedBuffer() : front(0), back(0), count(0) {}                  calling
      _Nomutex int query() { return count; }
      void insert( int elem ) {
           if ( count == 20 ) NonFull.wait();              shared data
           Elements[back] = elem;                         wait
           back = ( back + 1 ) % 20;                                    signal
           count += 1;
           NonEmpty.signal();                 NonEmpty
      }                                                   signalBlock             signalled
      int remove() {
           if ( count == 0 ) NonEmpty.wait();
           int elem = Elements[front];          NonFull
           front = ( front + 1 ) % 20;                           exit
           count -= 1;
           NonFull.signal();
           return elem;
      }
 };
180
• wait() blocks the current thread, and restarts a signalled task or implicitly
  releases the monitor lock.
• signal() unblocks the thread on the front of the condition queue after the
  signaller thread blocks or exits.
• signalBlock() unblocks the thread on the front of the condition queue and
  blocks the signaller thread.
• General Model
181
                                                                      entry
                                                                      queue
                                                    mutex
                                                                        b
                                                    queues
                                            X                 Y         d     order of
                                                b             d         c     arrival
                                                a             c         a
                              condition
 _Monitor Mon {                  A
                                                                                 acceptor/
      uCondition A, B;                                                           signalled
      ...                                                shared                  stack
    public:
      int X(. . .) {. . .}                              variables
      void Y(. . .) {. . .}
 };
                              condition
                                 B
                                                             exit
                                  active task          blocked task         duplicate
• The entry queue is a queue of all calling tasks in the order the calls
  were made to the monitor.
182
• explicit scheduling occurs when:
   – An accept statement blocks the active task on the acceptor stack and
     makes a task ready from the specified mutex member queue.
   – A signal moves a task from the specified condition to the signalled
     stack.
• implicit scheduling occurs when a task waits in or exits from a mutex
  member, and a new task is selected first from the A/S stack, then the
  entry queue.
                        internal scheduling (signal)
   explicit scheduling external scheduling (accept)
•
   implicit scheduling monitor selects (wait/exit)
• Use external scheduling unless:
   – scheduling depends on member parameter value(s), e.g., compatibility
     code for dating:
   – a task might be further blocked while in the monitor (e.g., wait for
     additional resources)
183
    _Monitor DatingService {
         uCondition girls[20], boys[20], exchange;
         int girlPhoneNo, boyPhoneNo;
       public:
         int girl( int phoneNo, int ccode ) {
              if ( boys[ccode].empty() ) {
                    girls[ccode].wait();
                    girlPhoneNo = phoneNo;
                    exchange.signal();
              } else {
                    girlPhoneNo = phoneNo;
                    boys[ccode].signal(); // signalBlock() & remove exchange
                    exchange.wait();
              }
              return boyPhoneNo;
         }
         int boy( int phoneNo, int ccode ) {
              // same as above, with boy/girl interchanged
         }
    };

• Use implicit mutex queues to prevent double (queueing) blocking.
184
6.5 Readers/Writer
• E.g. Readers and Writer Problem (Solution 3)
    _Monitor ReadersWriter {
         int rcnt, wcnt;
         uCondition readers, writers;
       public:
         ReadersWriter() : rcnt(0), wcnt(0) {}
         void startRead() {
              if ( wcnt != 0 | | ! writers.empty() ) readers.wait();
              rcnt += 1;
              readers.signal();
         }
         void endRead() {
              rcnt -= 1;
              if ( rcnt == 0 ) writers.signal();
         }
         void startWrite() {
              if ( wcnt !=0 | | rcnt != 0 ) writers.wait();
              wcnt = 1;
         }
         void endWrite() {
              wcnt = 0;
              if ( ! readers.empty() ) readers.signal();
              else writers.signal();
         }
    };
185
• Can the monitor read/write members perform the reading/writing?
• Has the same protocol problem as P and V.
    ReadersWriter rw;
         readers                      writers
    rw.startRead()               rw.startWrite()
    // read                      // write
    rw.endRead()                 rw.endWrite()
• Alternative interface:
    _Monitor ReadersWriter {
       _Mutex void startRead();
       _Mutex void endRead();
       _Mutex void startWrite();
       _Mutex void endWrite();
     public:
       _Nomutex void read(. . .) {
            startRead();
            // read
            endRead();
       }
       _Nomutex void write(. . .) {
            startWrite();
            // write
            endWrite();
       }
186
• E.g. Readers and Writer Problem (Solution 4)
    _Monitor ReadersWriter {
         int rcnt, wcnt;
         uCondition RWers;
         enum RW { READER, WRITER };
       public:
         ReadersWriter() : rcnt(0), wcnt(0) {}
         void startRead() {
              if ( wcnt !=0 | | !RWers.empty() ) RWers.wait( READER );
              rcnt += 1;
              if ( ! RWers.empty() && RWers.front() == READER ) RWers.signal();
         }
         void endRead() {
              rcnt -= 1;
              if ( rcnt == 0 ) RWers.signal();
         }
         void startWrite() {
              if ( wcnt != 0 | | rcnt != 0 ) RWers.wait( WRITER );
              wcnt = 1;
         }
         void endWrite() {
              wcnt = 0;
              RWers.signal();
         }
    };
187
            task1      task2      task3      task4      task5
           WRITER     READER     READER     WRITER    READER

   RWers   blocked    blocked    blocked    blocked    blocked



• E.g. Readers and Writer Problem (Solution 5)
    _Monitor ReadersWriter {
       int rcnt, wcnt;
     public:
       ReadersWriter() : rcnt(0), wcnt(0) {}
       void endRead() {
            rcnt -= 1;
       }
       void endWrite() {
            wcnt = 0;
       }
       void startRead() {
            if ( wcnt > 0 ) _Accept( endWrite );
            rcnt += 1;
       }
       void startWrite() {
            if ( wcnt > 0 ) { _Accept( endWrite ); } // braces needed
            else while ( rcnt > 0 ) _Accept( endRead );
            wcnt = 1;
       }
188
• Why has the order of the member routines changed?

6.6 Condition, Signal, Wait vs. Counting Semaphore, V, P
• There are several important differences between these mechanisms:
   – wait always blocks, P only blocks if semaphore = 0
   – if signal occurs before a wait, it is lost, while a V before a P affects the
     P
   – multiple Vs may start multiple tasks simultaneously, while multiple
     signals only start one task at a time because each task must exit
     serially through the monitor
• It is possible to construct P and V using a monitor:
189
    _Monitor semaphore {
        int sem;
        uCondition semcond;
     public:
        semaphore( int cnt = 1 ) : sem( cnt ) {}
        void P() {
             if ( sem == 0 ) semcond.wait();
             sem -= 1;
        }
        void V() {
             sem += 1;
             semcond.signal();
        }
    };

6.7 Monitor Types
• Monitors are classified by the implicit scheduling (who gets control) of
  the monitor when a task waits or signals or exits.
• Implicit scheduling can select from the calling (C), signalled (W) and
  signaller (S) queues.
190
                              calling (C)



                                                   signalled (W)

                                mutex
                                object
           conditions
                                variables


                                                   signaller (S)

                                   exit
                        active task         blocked task
– Assigning different priorities to these queues creates different
  monitors (e.g., C < W < S).
– Many of the possible orderings can be rejected as they do not produce
  a useful monitor (e.g., W < S < C).
191
• Implicit Signal
   – Monitors either have an explicit signal (statement) or an implicit
     signal (automatic signal).
   – The implicit signal monitor has no condition variables or explicit
     signal statement.
   – Instead, there is a waitUntil statement, e.g.:
      waitUntil logical-expression
  – The implicit signal causes a task to wait until the conditional
    expression is true.
192
_Monitor BoundedBuffer {
     int front, back, count;
     int Elements[20];
   public:
     BoundedBuffer() : front(0), back(0), count(0) {}
     _Nomutex int query() { return count; }
     void insert( int elem ) {
           waitUntil count != 20; // not in uC++
          Elements[back] = elem;
          back = ( back + 1 ) % 20;
          count += 1;
     }
     int remove() {
           waitUntil count != 0; // not in uC++
          int elem = Elements[front];
          front = ( front + 1 ) % 20;
          count -= 1;
          return elem;
     }
};
193
• There is a restricted monitor type that requires that the signaller exit
  immediately from the monitor (i.e., signal ⇒ return), called
  immediate-return signal.
• Ten kinds of useful monitor are suggested:
       signal type            priority              no priority
        Blocking    Priority Blocking (Hoare)  No Priority Blocking
                  C < S < W (µC+ signalBlock)
                                    +               C=S<W
      Nonblocking     Priority Nonblocking    No Priority Nonblocking
                    C < W < S (µC+ signal)
                                       +       C = W < S (Java/C#)
          Quasi            Priority Quasi        No Priority Quasi
        -blocking           C<W=S                   C=W=S
       Immediate          Priority Return       No Priority Return
          Return              C<W                      C=W
                              Priority              No Priority
         Implicit         Implicit Signal         Implicit Signal
          Signal              C<W                      C=W
  – No-priority monitors require the signalled task to recheck the waiting
    condition in case of a barging task.
    ⇒ use a while loop around a wait instead of an if
  – Implicit (automatic) signal monitors are good for prototyping but have
    poor performance.
194
   – Immediate-return monitors are not powerful enough to handle all
     cases but optimize the most common case of signal before return.
   – Quasi-blocking monitors makes cooperation too difficult.
   – priority-nonblocking monitor has no barging and optimizes signal
     before return (supply cooperation).
   – priority-blocking monitor has no barging and handles internal
     cooperation within the monitor (wait for cooperation).
• Java monitor
   – synchronized (wrong name) ⇒ mutex
   – only one condition variable per monitor
     (new Java library has multiple conditions but are incompatible with
     language condition)
   – condition operations: wait(), signal(), notifyall()
   – no-priority nonblocking monitor ⇒ while ( ! C ) wait();
• coroutine monitor
   – coroutine with implicit mutual exclusion on calls to specified member
     routines:
195
    _Mutex _Coroutine C { // _Cormonitor
         void main() {
                 . . . suspend() . . .
                 . . . suspend() . . .
         }
       public:
         void m1( . . . ) { . . . resume(); . . . } // mutual exclusion
         void m2( . . . ) { . . . resume(); . . . } // mutual exclusion
         . . . // destructor is ALWAYS mutex
    };
– can use resume(), suspend(), condition variables (wait(), signal(),
  signalBlock()) or _Accept on mutex members.
– coroutine can now be used by multiple threads, e.g., coroutine
  print-formatter accessed by multiple threads.

More Related Content

What's hot

Random stability in systemVerilog and UVM based testbench
Random stability in systemVerilog and UVM based testbenchRandom stability in systemVerilog and UVM based testbench
Random stability in systemVerilog and UVM based testbench
Kashyap Adodariya
 
Embedded systemsproject_2020
Embedded systemsproject_2020Embedded systemsproject_2020
Embedded systemsproject_2020
Nikos Mouzakitis
 
OpenCL 3.0 Reference Guide
OpenCL 3.0 Reference GuideOpenCL 3.0 Reference Guide
OpenCL 3.0 Reference Guide
The Khronos Group Inc.
 
Vulkan 1.1 Reference Guide
Vulkan 1.1 Reference GuideVulkan 1.1 Reference Guide
Vulkan 1.1 Reference Guide
The Khronos Group Inc.
 
Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6
fisher.w.y
 
Austin c-c++-meetup-feb2018-spectre
Austin c-c++-meetup-feb2018-spectreAustin c-c++-meetup-feb2018-spectre
Austin c-c++-meetup-feb2018-spectre
Kim Phillips
 
OpenCL 2.1 Reference Guide
OpenCL 2.1 Reference GuideOpenCL 2.1 Reference Guide
OpenCL 2.1 Reference Guide
The Khronos Group Inc.
 
Realisation de controlleur VGA(VHDL)
Realisation de controlleur VGA(VHDL)Realisation de controlleur VGA(VHDL)
Realisation de controlleur VGA(VHDL)
yahya ayari
 
Session 6 sv_randomization
Session 6 sv_randomizationSession 6 sv_randomization
Session 6 sv_randomization
Nirav Desai
 
Simware Simdeveloper
Simware SimdeveloperSimware Simdeveloper
Simware Simdeveloper
José Ramón Martínez Salio
 
Encryption Decryption Java Project by Devansh Koolwal
Encryption Decryption Java Project by Devansh KoolwalEncryption Decryption Java Project by Devansh Koolwal
Encryption Decryption Java Project by Devansh Koolwal
Devansh Koolwal
 
radix_4 fft dif with mdc and mdf
radix_4 fft dif with mdc and mdfradix_4 fft dif with mdc and mdf
radix_4 fft dif with mdc and mdf
sakthi1986
 
The OpenCL C++ Wrapper 1.2 Reference Card
The OpenCL C++ Wrapper 1.2 Reference CardThe OpenCL C++ Wrapper 1.2 Reference Card
The OpenCL C++ Wrapper 1.2 Reference Card
The Khronos Group Inc.
 
Bluespec @waseda
Bluespec @wasedaBluespec @waseda
Bluespec @waseda
Takefumi MIYOSHI
 
Introduccion a AspectJ
Introduccion a AspectJIntroduccion a AspectJ
Introduccion a AspectJ
Mauricio Quezada
 
Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++
Seok-joon Yun
 
OpenWF 1.0 Composition Reference Card
OpenWF 1.0 Composition Reference CardOpenWF 1.0 Composition Reference Card
OpenWF 1.0 Composition Reference Card
The Khronos Group Inc.
 
OpenVX 1.2 Reference Guide
OpenVX 1.2 Reference GuideOpenVX 1.2 Reference Guide
OpenVX 1.2 Reference Guide
The Khronos Group Inc.
 
OpenGL SC 2.0 Quick Reference
OpenGL SC 2.0 Quick ReferenceOpenGL SC 2.0 Quick Reference
OpenGL SC 2.0 Quick Reference
The Khronos Group Inc.
 
Sysprog 14
Sysprog 14Sysprog 14
Sysprog 14
Ahmed Mekkawy
 

What's hot (20)

Random stability in systemVerilog and UVM based testbench
Random stability in systemVerilog and UVM based testbenchRandom stability in systemVerilog and UVM based testbench
Random stability in systemVerilog and UVM based testbench
 
Embedded systemsproject_2020
Embedded systemsproject_2020Embedded systemsproject_2020
Embedded systemsproject_2020
 
OpenCL 3.0 Reference Guide
OpenCL 3.0 Reference GuideOpenCL 3.0 Reference Guide
OpenCL 3.0 Reference Guide
 
Vulkan 1.1 Reference Guide
Vulkan 1.1 Reference GuideVulkan 1.1 Reference Guide
Vulkan 1.1 Reference Guide
 
Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6Rootkit on Linux X86 v2.6
Rootkit on Linux X86 v2.6
 
Austin c-c++-meetup-feb2018-spectre
Austin c-c++-meetup-feb2018-spectreAustin c-c++-meetup-feb2018-spectre
Austin c-c++-meetup-feb2018-spectre
 
OpenCL 2.1 Reference Guide
OpenCL 2.1 Reference GuideOpenCL 2.1 Reference Guide
OpenCL 2.1 Reference Guide
 
Realisation de controlleur VGA(VHDL)
Realisation de controlleur VGA(VHDL)Realisation de controlleur VGA(VHDL)
Realisation de controlleur VGA(VHDL)
 
Session 6 sv_randomization
Session 6 sv_randomizationSession 6 sv_randomization
Session 6 sv_randomization
 
Simware Simdeveloper
Simware SimdeveloperSimware Simdeveloper
Simware Simdeveloper
 
Encryption Decryption Java Project by Devansh Koolwal
Encryption Decryption Java Project by Devansh KoolwalEncryption Decryption Java Project by Devansh Koolwal
Encryption Decryption Java Project by Devansh Koolwal
 
radix_4 fft dif with mdc and mdf
radix_4 fft dif with mdc and mdfradix_4 fft dif with mdc and mdf
radix_4 fft dif with mdc and mdf
 
The OpenCL C++ Wrapper 1.2 Reference Card
The OpenCL C++ Wrapper 1.2 Reference CardThe OpenCL C++ Wrapper 1.2 Reference Card
The OpenCL C++ Wrapper 1.2 Reference Card
 
Bluespec @waseda
Bluespec @wasedaBluespec @waseda
Bluespec @waseda
 
Introduccion a AspectJ
Introduccion a AspectJIntroduccion a AspectJ
Introduccion a AspectJ
 
Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++
 
OpenWF 1.0 Composition Reference Card
OpenWF 1.0 Composition Reference CardOpenWF 1.0 Composition Reference Card
OpenWF 1.0 Composition Reference Card
 
OpenVX 1.2 Reference Guide
OpenVX 1.2 Reference GuideOpenVX 1.2 Reference Guide
OpenVX 1.2 Reference Guide
 
OpenGL SC 2.0 Quick Reference
OpenGL SC 2.0 Quick ReferenceOpenGL SC 2.0 Quick Reference
OpenGL SC 2.0 Quick Reference
 
Sysprog 14
Sysprog 14Sysprog 14
Sysprog 14
 

Viewers also liked

Errors (Concurrency)
Errors (Concurrency)Errors (Concurrency)
Errors (Concurrency)
Sri Prasanna
 
Introduction to Concurrency
Introduction to ConcurrencyIntroduction to Concurrency
Introduction to Concurrency
Sri Prasanna
 
Locks (Concurrency)
Locks (Concurrency)Locks (Concurrency)
Locks (Concurrency)
Sri Prasanna
 
Direct Communications (Concurrency)
Direct Communications (Concurrency)Direct Communications (Concurrency)
Direct Communications (Concurrency)
Sri Prasanna
 
Concurrency
ConcurrencyConcurrency
Concurrency
Sri Prasanna
 
Other Approaches (Concurrency)
Other Approaches (Concurrency)Other Approaches (Concurrency)
Other Approaches (Concurrency)
Sri Prasanna
 
Coroutine (Concurrency)
Coroutine (Concurrency)Coroutine (Concurrency)
Coroutine (Concurrency)
Sri Prasanna
 
Qr codes para tech radar
Qr codes para tech radarQr codes para tech radar
Qr codes para tech radar
Sri Prasanna
 

Viewers also liked (8)

Errors (Concurrency)
Errors (Concurrency)Errors (Concurrency)
Errors (Concurrency)
 
Introduction to Concurrency
Introduction to ConcurrencyIntroduction to Concurrency
Introduction to Concurrency
 
Locks (Concurrency)
Locks (Concurrency)Locks (Concurrency)
Locks (Concurrency)
 
Direct Communications (Concurrency)
Direct Communications (Concurrency)Direct Communications (Concurrency)
Direct Communications (Concurrency)
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Other Approaches (Concurrency)
Other Approaches (Concurrency)Other Approaches (Concurrency)
Other Approaches (Concurrency)
 
Coroutine (Concurrency)
Coroutine (Concurrency)Coroutine (Concurrency)
Coroutine (Concurrency)
 
Qr codes para tech radar
Qr codes para tech radarQr codes para tech radar
Qr codes para tech radar
 

Similar to Indirect Communications (Concurrency)

Interesting facts on c
Interesting facts on cInteresting facts on c
Interesting facts on c
Durgadevi palani
 
Fpga creating counter with external clock
Fpga   creating counter with external clockFpga   creating counter with external clock
Fpga creating counter with external clock
Politeknik Elektronika Negeri Surabaya
 
Day2 Verilog HDL Basic
Day2 Verilog HDL BasicDay2 Verilog HDL Basic
Day2 Verilog HDL Basic
Ron Liu
 
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptxWINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
ssusercd11c4
 
Lecture 2 verilog
Lecture 2   verilogLecture 2   verilog
Lecture 2 verilog
venravi10
 
ES-CH6.ppt
ES-CH6.pptES-CH6.ppt
ES-CH6.ppt
alaakaraja1
 
Appsec obfuscator reloaded
Appsec obfuscator reloadedAppsec obfuscator reloaded
Appsec obfuscator reloaded
Cyber Security Alliance
 
TLPI - 6 Process
TLPI - 6 ProcessTLPI - 6 Process
TLPI - 6 Process
Shu-Yu Fu
 
Practical file
Practical filePractical file
Practical file
rajeevkr35
 
Slides13.pdf
Slides13.pdfSlides13.pdf
Slides13.pdf
ssuser3b4934
 
C++InputOutput.pptx
C++InputOutput.pptxC++InputOutput.pptx
C++InputOutput.pptx
ansariparveen06
 
For Coordination, State Component Transitions - Radoslaw Szymanek, Simon Bliudze
For Coordination, State Component Transitions - Radoslaw Szymanek, Simon BliudzeFor Coordination, State Component Transitions - Radoslaw Szymanek, Simon Bliudze
For Coordination, State Component Transitions - Radoslaw Szymanek, Simon Bliudze
mfrancis
 
OS_Ch7
OS_Ch7OS_Ch7
OSCh7
OSCh7OSCh7
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2
ppd1961
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기
Ji Hun Kim
 
Verilog hdl
Verilog hdlVerilog hdl
Taming event-driven software via formal verification
Taming event-driven software via formal verificationTaming event-driven software via formal verification
Taming event-driven software via formal verification
AdaCore
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
EasyStudy3
 
hdl timer ppt.pptx
hdl timer ppt.pptxhdl timer ppt.pptx
hdl timer ppt.pptx
ChethaSp
 

Similar to Indirect Communications (Concurrency) (20)

Interesting facts on c
Interesting facts on cInteresting facts on c
Interesting facts on c
 
Fpga creating counter with external clock
Fpga   creating counter with external clockFpga   creating counter with external clock
Fpga creating counter with external clock
 
Day2 Verilog HDL Basic
Day2 Verilog HDL BasicDay2 Verilog HDL Basic
Day2 Verilog HDL Basic
 
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptxWINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
WINSEM2016-17_CSE1002_LO_1336_24-JAN-2017_RM003_session 10.pptx
 
Lecture 2 verilog
Lecture 2   verilogLecture 2   verilog
Lecture 2 verilog
 
ES-CH6.ppt
ES-CH6.pptES-CH6.ppt
ES-CH6.ppt
 
Appsec obfuscator reloaded
Appsec obfuscator reloadedAppsec obfuscator reloaded
Appsec obfuscator reloaded
 
TLPI - 6 Process
TLPI - 6 ProcessTLPI - 6 Process
TLPI - 6 Process
 
Practical file
Practical filePractical file
Practical file
 
Slides13.pdf
Slides13.pdfSlides13.pdf
Slides13.pdf
 
C++InputOutput.pptx
C++InputOutput.pptxC++InputOutput.pptx
C++InputOutput.pptx
 
For Coordination, State Component Transitions - Radoslaw Szymanek, Simon Bliudze
For Coordination, State Component Transitions - Radoslaw Szymanek, Simon BliudzeFor Coordination, State Component Transitions - Radoslaw Szymanek, Simon Bliudze
For Coordination, State Component Transitions - Radoslaw Szymanek, Simon Bliudze
 
OS_Ch7
OS_Ch7OS_Ch7
OS_Ch7
 
OSCh7
OSCh7OSCh7
OSCh7
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2
 
Windbg랑 친해지기
Windbg랑 친해지기Windbg랑 친해지기
Windbg랑 친해지기
 
Verilog hdl
Verilog hdlVerilog hdl
Verilog hdl
 
Taming event-driven software via formal verification
Taming event-driven software via formal verificationTaming event-driven software via formal verification
Taming event-driven software via formal verification
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
hdl timer ppt.pptx
hdl timer ppt.pptxhdl timer ppt.pptx
hdl timer ppt.pptx
 

More from Sri Prasanna

Qr codes para tech radar 2
Qr codes para tech radar 2Qr codes para tech radar 2
Qr codes para tech radar 2
Sri Prasanna
 
Test
TestTest
Test
TestTest
assds
assdsassds
assds
assdsassds
asdsa
asdsaasdsa
dsd
dsddsd
About stacks
About stacksAbout stacks
About stacks
Sri Prasanna
 
About Stacks
About  StacksAbout  Stacks
About Stacks
Sri Prasanna
 
About Stacks
About  StacksAbout  Stacks
About Stacks
Sri Prasanna
 
About Stacks
About  StacksAbout  Stacks
About Stacks
Sri Prasanna
 
About Stacks
About  StacksAbout  Stacks
About Stacks
Sri Prasanna
 
About Stacks
About  StacksAbout  Stacks
About Stacks
Sri Prasanna
 
About Stacks
About StacksAbout Stacks
About Stacks
Sri Prasanna
 
About Stacks
About StacksAbout Stacks
About Stacks
Sri Prasanna
 
Network and distributed systems
Network and distributed systemsNetwork and distributed systems
Network and distributed systems
Sri Prasanna
 
Introduction & Parellelization on large scale clusters
Introduction & Parellelization on large scale clustersIntroduction & Parellelization on large scale clusters
Introduction & Parellelization on large scale clusters
Sri Prasanna
 
Mapreduce: Theory and implementation
Mapreduce: Theory and implementationMapreduce: Theory and implementation
Mapreduce: Theory and implementation
Sri Prasanna
 
Other distributed systems
Other distributed systemsOther distributed systems
Other distributed systems
Sri Prasanna
 
Distributed file systems
Distributed file systemsDistributed file systems
Distributed file systems
Sri Prasanna
 

More from Sri Prasanna (20)

Qr codes para tech radar 2
Qr codes para tech radar 2Qr codes para tech radar 2
Qr codes para tech radar 2
 
Test
TestTest
Test
 
Test
TestTest
Test
 
assds
assdsassds
assds
 
assds
assdsassds
assds
 
asdsa
asdsaasdsa
asdsa
 
dsd
dsddsd
dsd
 
About stacks
About stacksAbout stacks
About stacks
 
About Stacks
About  StacksAbout  Stacks
About Stacks
 
About Stacks
About  StacksAbout  Stacks
About Stacks
 
About Stacks
About  StacksAbout  Stacks
About Stacks
 
About Stacks
About  StacksAbout  Stacks
About Stacks
 
About Stacks
About  StacksAbout  Stacks
About Stacks
 
About Stacks
About StacksAbout Stacks
About Stacks
 
About Stacks
About StacksAbout Stacks
About Stacks
 
Network and distributed systems
Network and distributed systemsNetwork and distributed systems
Network and distributed systems
 
Introduction & Parellelization on large scale clusters
Introduction & Parellelization on large scale clustersIntroduction & Parellelization on large scale clusters
Introduction & Parellelization on large scale clusters
 
Mapreduce: Theory and implementation
Mapreduce: Theory and implementationMapreduce: Theory and implementation
Mapreduce: Theory and implementation
 
Other distributed systems
Other distributed systemsOther distributed systems
Other distributed systems
 
Distributed file systems
Distributed file systemsDistributed file systems
Distributed file systems
 

Recently uploaded

5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!
GDSC PJATK
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
Dinusha Kumarasiri
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
alexjohnson7307
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Tatiana Kojar
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Jeffrey Haguewood
 

Recently uploaded (20)

5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...
 
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
 

Indirect Communications (Concurrency)

  • 1. 6 Indirect Communication • P and V are low level primitives for protecting critical sections and establishing synchronization between tasks. • Shared variables provide the actual information that is communicated. • Both of these can be complicated to use and may be incorrectly placed. • Split-binary semaphores and baton passing are complex. • Need higher level facilities that perform some of these details automatically. • Get help from programming-language/compiler. 6.1 Critical Regions • Declare which variables are to be shared, as in: VAR v : SHARED INTEGER • Access to shared variables is restricted to within a REGION statement, and within the region, mutual exclusion is guaranteed. Except as otherwise noted, the content of this presentation is licensed under the Creative Com- mons Attribution 2.5 License. 169
  • 2. 170 semaphore v_lock(1); REGION v DO P(v_lock) // critical section ... // x = v; (read) v = y (write) END REGION V(v_lock) • Nesting can result in deadlock. VAR x, y : SHARED INTEGER task1 task2 REGION x DO REGION y DO ... ... REGION y DO REGION x DO ... ... END REGION END REGION ... ... END REGION END REGION • Simultaneous reads are impossible! • Modify to allow reading of shared variables outside the critical region and modifications in the region. • Problem: reading partially updated information while a task is updating
  • 3. 171 the shared variable in the region. 6.2 Conditional Critical Regions • Introduce a condition that must be true as well as having mutual exclusion. REGION v DO AWAIT conditional-expression ... END REGION • E.g. The consumer from the producer-consumer problem. VAR Q : SHARED QUEUE<INT,10> REGION Q DO AWAIT NOT EMPTY( Q ) buffer not empty take an item from the front of the queue END REGION If the condition is false, the region lock is released and entry is started again (busy waiting).
  • 4. 172 6.3 Monitor • A monitor is an abstract data type that combines shared data with serialization of its modification. _Monitor name { shared data members that see and modify the data }; • A mutex member (short for mutual-exclusion member) is one that does NOT begin execution if there is another active mutex member. – ⇒ a call to a mutex member may become blocked waiting entry, and queues of waiting tasks may form. – Public member routines of a monitor are implicitly mutex and other kinds of members can be made explicitly mutex ( _Mutex). • Basically each monitor has a lock which is Ped on entry to a monitor member and Ved on exit.
  • 5. 173 class Mon { int v; uSemaphore MonitorLock(1) public: int x(. . .) { MonitorLock.P() ... // int temp = v; MonitorLock.V() return v; // return temp; } • Unhandled exceptions raised within a monitor always release the implicit monitor locks so the monitor can continue to function. • Atomic counter using a monitor:
  • 6. 174 _Monitor AtomicCounter { int counter; public: AtomicCounter( int init ) : counter( init ) {} int inc() { counter += 1; return counter; } int dec() { counter -= 1; return counter; } }; AtomicCounter a, b, c; . . . a.inc(); . . . . . . b.dec(); . . . . . . c.inc(); . . . • Recursive entry is allowed (owner mutex lock), i.e., one mutex member can call another or itself. • Destructor is mutex, so ending a block with a monitor or deleting a dynamically allocated monitor, blocks if thread in monitor. 6.4 Scheduling (Synchronization) • A monitor may want to schedule tasks in an order different from the order in which they arrive.
  • 7. 175 • There are two techniques: external and internal scheduling. – external is scheduling tasks outside the monitor and is accomplished with the accept statement. – internal is scheduling tasks inside the monitor and is accomplished using condition variables with signal & wait. 6.4.1 External Scheduling • The accept statement controls which mutex members can accept calls. • By preventing certain members from accepting calls at different times, it is possible to control scheduling of tasks. • E.g. Bounded Buffer
  • 8. 176 b _Monitor BoundedBuffer { mutex routines calling int front, back, count; insert remove d int Elements[20]; b d c public: BoundedBuffer() : front(0), back(0), count(0) {} c a a _Nomutex int query() { return count; } [_Mutex] void insert( int elem ); shared data [_Mutex] int remove(); }; acceptor void BoundedBuffer::insert( int elem ) { if ( count == 20 ) _Accept( remove ); // hold insert calls exit Elements[back] = elem; back = ( back + 1 ) % 20; count += 1; } int BoundedBuffer::remove() { if ( count == 0 ) _ Accept( insert ); // hold remove calls int elem = Elements[front]; front = ( front + 1 ) % 20; count -= 1; return elem; }
  • 9. 177 • Queues of tasks form outside the monitor, waiting to be accepted into either insert or remove. • An acceptor blocks until a call to the specified mutex member(s) occurs. • Accepted call is executed like a conventional member call. • When the accepted task exits the mutex member (or blocks), the acceptor continues. • If the accepted task does an accept, it blocks, forming a stack of blocked acceptors. 6.4.2 Internal Scheduling • Scheduling among tasks inside the monitor. • A condition is a queue of waiting tasks: uCondition x, y, z[5]; • A task waits (blocks) by placing itself on a condition: x.wait(); // wait( mutex, condition ) Atomically places the executing task at the back of the condition queue, and allows another task into the monitor by releasing the monitor lock.
  • 10. 178 • A task on a condition queue is made ready by signalling the condition: x.signal(); This removes a blocked task at the front of the condition queue and makes it ready. • Like Ving a semaphore, the signaller does not block, so the signalled task must continue waiting until the signaller exits or waits. • A signal on an empty condition is lost!
  • 11. 179 • E.g. Bounded Buffer (like binary semaphore solution): _Monitor BoundedBuffer { uCondition NonEmpty, NonFull; int front, back, count; int Elements[20]; public: BoundedBuffer() : front(0), back(0), count(0) {} calling _Nomutex int query() { return count; } void insert( int elem ) { if ( count == 20 ) NonFull.wait(); shared data Elements[back] = elem; wait back = ( back + 1 ) % 20; signal count += 1; NonEmpty.signal(); NonEmpty } signalBlock signalled int remove() { if ( count == 0 ) NonEmpty.wait(); int elem = Elements[front]; NonFull front = ( front + 1 ) % 20; exit count -= 1; NonFull.signal(); return elem; } };
  • 12. 180 • wait() blocks the current thread, and restarts a signalled task or implicitly releases the monitor lock. • signal() unblocks the thread on the front of the condition queue after the signaller thread blocks or exits. • signalBlock() unblocks the thread on the front of the condition queue and blocks the signaller thread. • General Model
  • 13. 181 entry queue mutex b queues X Y d order of b d c arrival a c a condition _Monitor Mon { A acceptor/ uCondition A, B; signalled ... shared stack public: int X(. . .) {. . .} variables void Y(. . .) {. . .} }; condition B exit active task blocked task duplicate • The entry queue is a queue of all calling tasks in the order the calls were made to the monitor.
  • 14. 182 • explicit scheduling occurs when: – An accept statement blocks the active task on the acceptor stack and makes a task ready from the specified mutex member queue. – A signal moves a task from the specified condition to the signalled stack. • implicit scheduling occurs when a task waits in or exits from a mutex member, and a new task is selected first from the A/S stack, then the entry queue. internal scheduling (signal) explicit scheduling external scheduling (accept) • implicit scheduling monitor selects (wait/exit) • Use external scheduling unless: – scheduling depends on member parameter value(s), e.g., compatibility code for dating: – a task might be further blocked while in the monitor (e.g., wait for additional resources)
  • 15. 183 _Monitor DatingService { uCondition girls[20], boys[20], exchange; int girlPhoneNo, boyPhoneNo; public: int girl( int phoneNo, int ccode ) { if ( boys[ccode].empty() ) { girls[ccode].wait(); girlPhoneNo = phoneNo; exchange.signal(); } else { girlPhoneNo = phoneNo; boys[ccode].signal(); // signalBlock() & remove exchange exchange.wait(); } return boyPhoneNo; } int boy( int phoneNo, int ccode ) { // same as above, with boy/girl interchanged } }; • Use implicit mutex queues to prevent double (queueing) blocking.
  • 16. 184 6.5 Readers/Writer • E.g. Readers and Writer Problem (Solution 3) _Monitor ReadersWriter { int rcnt, wcnt; uCondition readers, writers; public: ReadersWriter() : rcnt(0), wcnt(0) {} void startRead() { if ( wcnt != 0 | | ! writers.empty() ) readers.wait(); rcnt += 1; readers.signal(); } void endRead() { rcnt -= 1; if ( rcnt == 0 ) writers.signal(); } void startWrite() { if ( wcnt !=0 | | rcnt != 0 ) writers.wait(); wcnt = 1; } void endWrite() { wcnt = 0; if ( ! readers.empty() ) readers.signal(); else writers.signal(); } };
  • 17. 185 • Can the monitor read/write members perform the reading/writing? • Has the same protocol problem as P and V. ReadersWriter rw; readers writers rw.startRead() rw.startWrite() // read // write rw.endRead() rw.endWrite() • Alternative interface: _Monitor ReadersWriter { _Mutex void startRead(); _Mutex void endRead(); _Mutex void startWrite(); _Mutex void endWrite(); public: _Nomutex void read(. . .) { startRead(); // read endRead(); } _Nomutex void write(. . .) { startWrite(); // write endWrite(); }
  • 18. 186 • E.g. Readers and Writer Problem (Solution 4) _Monitor ReadersWriter { int rcnt, wcnt; uCondition RWers; enum RW { READER, WRITER }; public: ReadersWriter() : rcnt(0), wcnt(0) {} void startRead() { if ( wcnt !=0 | | !RWers.empty() ) RWers.wait( READER ); rcnt += 1; if ( ! RWers.empty() && RWers.front() == READER ) RWers.signal(); } void endRead() { rcnt -= 1; if ( rcnt == 0 ) RWers.signal(); } void startWrite() { if ( wcnt != 0 | | rcnt != 0 ) RWers.wait( WRITER ); wcnt = 1; } void endWrite() { wcnt = 0; RWers.signal(); } };
  • 19. 187 task1 task2 task3 task4 task5 WRITER READER READER WRITER READER RWers blocked blocked blocked blocked blocked • E.g. Readers and Writer Problem (Solution 5) _Monitor ReadersWriter { int rcnt, wcnt; public: ReadersWriter() : rcnt(0), wcnt(0) {} void endRead() { rcnt -= 1; } void endWrite() { wcnt = 0; } void startRead() { if ( wcnt > 0 ) _Accept( endWrite ); rcnt += 1; } void startWrite() { if ( wcnt > 0 ) { _Accept( endWrite ); } // braces needed else while ( rcnt > 0 ) _Accept( endRead ); wcnt = 1; }
  • 20. 188 • Why has the order of the member routines changed? 6.6 Condition, Signal, Wait vs. Counting Semaphore, V, P • There are several important differences between these mechanisms: – wait always blocks, P only blocks if semaphore = 0 – if signal occurs before a wait, it is lost, while a V before a P affects the P – multiple Vs may start multiple tasks simultaneously, while multiple signals only start one task at a time because each task must exit serially through the monitor • It is possible to construct P and V using a monitor:
  • 21. 189 _Monitor semaphore { int sem; uCondition semcond; public: semaphore( int cnt = 1 ) : sem( cnt ) {} void P() { if ( sem == 0 ) semcond.wait(); sem -= 1; } void V() { sem += 1; semcond.signal(); } }; 6.7 Monitor Types • Monitors are classified by the implicit scheduling (who gets control) of the monitor when a task waits or signals or exits. • Implicit scheduling can select from the calling (C), signalled (W) and signaller (S) queues.
  • 22. 190 calling (C) signalled (W) mutex object conditions variables signaller (S) exit active task blocked task – Assigning different priorities to these queues creates different monitors (e.g., C < W < S). – Many of the possible orderings can be rejected as they do not produce a useful monitor (e.g., W < S < C).
  • 23. 191 • Implicit Signal – Monitors either have an explicit signal (statement) or an implicit signal (automatic signal). – The implicit signal monitor has no condition variables or explicit signal statement. – Instead, there is a waitUntil statement, e.g.: waitUntil logical-expression – The implicit signal causes a task to wait until the conditional expression is true.
  • 24. 192 _Monitor BoundedBuffer { int front, back, count; int Elements[20]; public: BoundedBuffer() : front(0), back(0), count(0) {} _Nomutex int query() { return count; } void insert( int elem ) { waitUntil count != 20; // not in uC++ Elements[back] = elem; back = ( back + 1 ) % 20; count += 1; } int remove() { waitUntil count != 0; // not in uC++ int elem = Elements[front]; front = ( front + 1 ) % 20; count -= 1; return elem; } };
  • 25. 193 • There is a restricted monitor type that requires that the signaller exit immediately from the monitor (i.e., signal ⇒ return), called immediate-return signal. • Ten kinds of useful monitor are suggested: signal type priority no priority Blocking Priority Blocking (Hoare) No Priority Blocking C < S < W (µC+ signalBlock) + C=S<W Nonblocking Priority Nonblocking No Priority Nonblocking C < W < S (µC+ signal) + C = W < S (Java/C#) Quasi Priority Quasi No Priority Quasi -blocking C<W=S C=W=S Immediate Priority Return No Priority Return Return C<W C=W Priority No Priority Implicit Implicit Signal Implicit Signal Signal C<W C=W – No-priority monitors require the signalled task to recheck the waiting condition in case of a barging task. ⇒ use a while loop around a wait instead of an if – Implicit (automatic) signal monitors are good for prototyping but have poor performance.
  • 26. 194 – Immediate-return monitors are not powerful enough to handle all cases but optimize the most common case of signal before return. – Quasi-blocking monitors makes cooperation too difficult. – priority-nonblocking monitor has no barging and optimizes signal before return (supply cooperation). – priority-blocking monitor has no barging and handles internal cooperation within the monitor (wait for cooperation). • Java monitor – synchronized (wrong name) ⇒ mutex – only one condition variable per monitor (new Java library has multiple conditions but are incompatible with language condition) – condition operations: wait(), signal(), notifyall() – no-priority nonblocking monitor ⇒ while ( ! C ) wait(); • coroutine monitor – coroutine with implicit mutual exclusion on calls to specified member routines:
  • 27. 195 _Mutex _Coroutine C { // _Cormonitor void main() { . . . suspend() . . . . . . suspend() . . . } public: void m1( . . . ) { . . . resume(); . . . } // mutual exclusion void m2( . . . ) { . . . resume(); . . . } // mutual exclusion . . . // destructor is ALWAYS mutex }; – can use resume(), suspend(), condition variables (wait(), signal(), signalBlock()) or _Accept on mutex members. – coroutine can now be used by multiple threads, e.g., coroutine print-formatter accessed by multiple threads.