Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Benemérita Universidad Autónoma del
Estado de Puebla
Facultad de Cs. De la Computación
Programación Concurrente y Paralela
Productor - Consumidor
Profr:
María del Carmen Cerón Garnica
Alumnos:
Roberto Alejandro Bravo Arredondo
Aldo Flores Aparicio
Matricula:
200824268
200834334
29 de noviembre de 2011
1
SOLUCION SINCRONIZADA
Clase Buffer
public class Buffer { // no es un Thead
private int cima, capacidad, vector[];
Buffer (int i) {
cima = 0;
capacidad = i;
vector = new int[i];
}
synchronized public int extraer ( ) {
while (cima == 0)
try {
wait();
} catch (InterruptedException e){;}
notifyAll();
return vector[--cima];
}
synchronized public void insertar (int elem) {
while (cima==capacidad-1)
try {
wait();
} catch (InterruptedException e){;}
vector[cima]=elem;
cima++;
notifyAll();
}
}
Clase Consumidor
public class Consumidor extends Thread {
int elem;
Buffer buffer;
Consumidor (Buffer b, int i) {
buffer = b;
}
public void run ( ) {
try {
elem = buffer.extraer();
System.out.println("\nExtraje un elemento\n");
} catch (Exception e) {}
return;
}
}
2
Clase Productor
public class Productor extends Thread {
Buffer buffer;
int elem;
Productor (Buffer b, int i) {
elem=i;
buffer = b;
System.out.println ("Entra el productor "+i);
}
public void run ( ) {
try {
buffer.insertar(elem);
System.out.println("\n Inserté un elemento\n");
} catch (Exception e) {}
System.out.println ("he puesto el elemento "+elem);
return;
}
}
Clase ProductorConsumidor
public class ProductorConsumidor {
static Buffer buf = new Buffer(3);
public static void main (String[] args ) {
for (int i=1;i<=5;i++)
new Productor (buf,i).start();
for (int j=1;j<=5;j++)
new Consumidor (buf,j).start();
System.out.println ("Fin del hilo main");
}
}
3
Corrida Productor-Consumidor Sincronizado
4
SOLUCION CON SEMAFOROS
Clase CountingSemaphore
public final class CountingSemaphore extends Semaphore {
public CountingSemaphore() {super();} // constructors
public CountingSemaphore(int initial) {super(initial);}
}
Clase BinarySemaphore
public final class BinarySemaphore extends Semaphore {
public BinarySemaphore() {super();} // constructors
public BinarySemaphore(int initial) {
super(initial);
// Don't be silent about bad initial value; tell the user!
if (initial > 1) throw new IllegalArgumentException("initial>1");
}
public BinarySemaphore(boolean initial) {super(initial ? 1:0);}
public final synchronized void V() {
super.V();
if (value > 1) value = 1; // cap the value
}
}
Clase MyObject
public abstract class MyObject extends Object{
private static final long startTime = System.currentTimeMillis();
protected static final long age() { return System.currentTimeMillis() - startTime;
protected static final int nap(int napTimeMS) {
long napStart = age();
try {
Thread.sleep(napTimeMS);
}
catch (InterruptedException e) { System.err.println("interrupted out of sleep");
return (int) (age() - napStart - (long) napTimeMS);
}
}
}
protected static final void P(Semaphore s){s.P();}
protected static final void V(Semaphore s){s.V();}
}
5
Clase Semaphore
public abstract class Semaphore {
// if value < 0, then abs(value) is the size of the P() queue
protected int value = 0;
protected Semaphore() {value = 0;}
// protected Semaphore(int initial) {value = (initial > 0) ? initial : 0;}
protected Semaphore(int initial) {
// Don't be silent about bad initial value; tell the user!
if (initial < 0) throw new IllegalArgumentException("initial<0");
value = initial;
}
public synchronized void P() {
value--;
if (value < 0) {
while (true) { // we must be notified not interrupted
try {
wait();
break;
// notify(), so P() succeeds
} catch (InterruptedException e) {
System.err.println
("Semaphore.P(): InterruptedException, wait again");
if (value >= 0) break; // race condition fix
else continue;
// no V() yet
}
}
}
}
public synchronized void V() { // this technique prevents
value++;
// barging since any caller of
if (value <= 0) notify(); // P() will wait even if it
}
// enters before signaled thread
// do not do a `if (S.value() > 0) S.P(); else ...'
// because there is a race condition; use S.tryP() instead
public synchronized int value() {
return value;
}
public synchronized String toString() {
return String.valueOf(value);
}
}
6
Clase Productor-Consumidor
import java.io.*;
class almacen extends MyObject {
private CountingSemaphore elementos = null;
private CountingSemaphore espacios = null;
private BinarySemaphore mutex = null;
private int valor;
private int count = 0;
public almacen(){
mutex = new BinarySemaphore(1);
elementos = new CountingSemaphore(0);
espacios = new CountingSemaphore(5);
valor = 0;
}
public void poner(int x){
P(espacios);
valor = x;
P(mutex);
count ++;
V(mutex);
V(elementos);
}
public int extraer(){
P(elementos);
P(mutex);
count --;
V(mutex);
V(espacios);
return valor;
}
}
class Productor extends MyObject implements Runnable {
private almacen alm = null;
public Productor(almacen almi){ this.alm = almi; }
public void run() {
int i=1;
//for(int i=1; i<=5; i++) {
while(true){
alm.poner(i);
System.out.println("Se produjo: " +i);
i++;
nap(500);
}
}
}
class Consumidor extends MyObject implements Runnable {
private almacen alm = null;
public Consumidor(almacen almi){ this.alm = almi; }
public void run() {
int ext,i=1;
//for(int i=1; i<=5; i++) {
while(true){
//nap(3000);
ext=alm.extraer();
System.out.println("Se Consumio: " +i);
i++;
nap(500);
}
}
}
7
class ProductorConsumidor extends MyObject {
public static void main(String args[]) {
almacen a = new almacen();
Thread p = new Thread(new Productor(a));
Thread c = new Thread(new Consumidor(a));
p.start();
c.start();
System.out.println("Tolos los hilos iniciados");
nap(3000);
p.stop();
c.stop();
System.exit(0);
}
}
8
Corrida Productor-Consumidor con Semaforo
9
SOLUCION CON MONITORES
Clase ConditionVariable
public class ConditionVariable { // not yet implemented
public void waitCV(Object monitor) {try {monitor.wait();}
catch (InterruptedException e)
{System.out.println("error "+e.toString());}
}
public void notifyCV(Object monitor) {monitor.notify();}
public boolean emptyCV(Object monitor) {return true;}
}
Clase Almacen
class almacen extends MyObject
{
private int valor;
private ConditionVariable produce = null;
private ConditionVariable consume = null;
public almacen()
{
valor=0;
produce = new ConditionVariable();
consume = new ConditionVariable();
}
public synchronized void poner(int v)
{
while(valor!=0)
wait(produce);
valor=v;
notify(consume);
}
public synchronized int sacar()
{
while(valor==0)
wait(consume);
int temp=valor;
valor=0;
notify(produce);
return temp;
}
}
Clase Consumidor
class consumidor extends MyObject implements Runnable
{
private almacen alm;
public consumidor(almacen a1){ alm=a1; }
//constructor
public void run()
{
int temp;
for(int i =1; i<=10; i++)
{
temp=alm.sacar();
System.out.println("\t\tConsumiendo "+temp);
nap(500);
}
}
}
10
Clase MyObject
import java.io.Serializable;
import java.util.Date;
import java.util.Random;
public abstract class MyObject extends Object implements Serializable {
private static final String OSname = System.getProperty("os.name");
private static int timeSlice = 100;
private static boolean timeSlicingEnsured = false;
private static final long startTime = System.currentTimeMillis();
private static final Random rnd = new Random();
private String name = "MyObject";
protected MyObject() {super();} // this class is designed
// to be extended only
protected MyObject(String name) {
super();
this.name = name;
}
protected static final String getOSname() {return OSname;}
protected final String getName() {return name;}
protected static final String getThreadName() {
return Thread.currentThread().getName();
}
protected static final long age() {
return System.currentTimeMillis() - startTime;
}
protected static final int nap(int napTimeMS) {
long napStart = age();
try {
Thread.sleep(napTimeMS);
} catch (InterruptedException e) {
//
System.err.println("interrupted out of sleep");
}
return (int) (age() - napStart - (long) napTimeMS);
}
protected static final void seed(long theSeed)
{ rnd.setSeed(theSeed); }
protected static final void seed(int theSeed)
{ rnd.setSeed((long)theSeed); }
protected static final void seed(float theSeed)
{ rnd.setSeed((long)theSeed); }
protected static final void seed(double theSeed)
{ rnd.setSeed((long)theSeed); }
// returns double in range [0, 1)
protected static final double random() {
return rnd.nextDouble();
}
// returns double in range [0, ub)
protected static final double random(int ub) {
return rnd.nextDouble()*ub;
}
11
// returns double in range [lb, ub)
protected static final double random(int lb, int ub) {
return lb + rnd.nextDouble()*(ub - lb);
}
protected final void wait(ConditionVariable cv)
{ cv.waitCV(this); }
protected final void notify(ConditionVariable cv)
{ cv.notifyCV(this); }
protected final boolean empty(ConditionVariable cv)
{ return cv.emptyCV(this); }
}
Clase Productor
class productor extends MyObject implements Runnable
{
private almacen alm;
public productor(almacen a1){ alm=a1; }
//constructor
public void run()
{
for(int i =1; i<=10; i++)
{
System.out.println("Produciendo "+i );
alm.poner(i);
nap(500);
}
}
}
Clase Productor_Consumidor
import java.io.*;
import java.lang.*;
public class Productor_Consumdidor extends MyObject
{
public static void main(String[] args)
{
almacen a = new almacen();
Thread p = new Thread ( new productor(a) );
Thread c = new Thread ( new consumidor(a) );
p.start();
c.start();
}
}
12
Corrida Producto-Consumidor con Monitores
13