Presentation is loading. Please wait.

Presentation is loading. Please wait.

Monitors.

Similar presentations


Presentation on theme: "Monitors."— Presentation transcript:

1 Monitors

2 Monitors - definition 1 In concurrent programming, a monitor is a synchronization construct that allows threads to have both mutual exclusion and the ability to wait (block) for a certain condition to become true. Monitors also have a mechanism for signaling other threads that their condition has been met. A monitor consists of a mutex (lock) object and condition variables

3 Monitors - definition 2 Another definition of monitor is a thread-safe class, object, or module that uses wrapped mutual exclusion in order to safely allow access to a method or variable by more than one thread. The defining characteristic of a monitor is that its methods are executed with mutual exclusion: At each point in time, at most one thread may be executing any of its methods.

4 Home made monitor class
class Account { private semaphore accountSemaphore; // not static…one for every object public void withdraw(int amount) { P(accountSemaphore); balance = balance – amount; V(accountSemaphore); } public void deposit(int amount) balance = balance + amount;

5 Monitor class monitor class Account { public void withdraw(int amount) { balance = balance – amount; } public void deposit(int amount) balance = balance + amount;

6 Producer- Consumer Monitor
monitor class dijkstraPC { public void producer(int amount) { while(1) while (queue.isFull()) { //busy waiting }; queue.enqueue(produced Stuff); }

7 Producer- Consumer Monitor
public void consumer(int amount) { while(1) while (queue.isEmpty()) { // busy waiting }; queue.dequeue(comsume stuff); }

8 Spin-waiting In the producer-consumer monitor example, while the producer is waiting for the isFull() condition to be met, it is locking out the consumers from empting out the buffers. while (queue.isFull()) { V(monitor.semaphore); // a chance some other thread may empty a buffer P(monitor.semaphore); };

9 Condition Variables public void producer(int amount) { while(1) while (queue.isFull()) CP(monitor.semaphore, bufferFull.semaphore); }; queue.enqueue(produced Stuff); }

10 Synchronization in Java
class X { private int a; private int b; public synchronized void addA(){ a++; } public synchronized void addB(){ b++; } // one thread is adding to a, it blocks thread adding to b

11 Synchronized method per object
public void addA() { synchronized( a ) { a++; } public void addB() { synchronized( b ) { b++; } // not allowed in Java because a and b are primitives.

12 Java Atomic Primitives
import java.util.concurrent.atomic.AtomicInteger; class X { AtomicInteger a; AtomicInteger b; public void addA(){ a.increment(); } public void addB(){ b.increment();


Download ppt "Monitors."

Similar presentations


Ads by Google