Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ejercicios;
- import static es.urjc.etsii.code.concurrency.SimpleConcurrent.*;
- import java.util.Arrays;
- import es.urjc.etsii.code.concurrency.SimpleSemaphore;
- public class practica1 {
- public static final int N_PROCESOS = 5;
- public static final int N_DATOS = 16;
- public static int nPares = 8;
- public static int procesosEnEspera = 0;
- private static SimpleSemaphore mutex1;
- private static SimpleSemaphore mutex2;
- private static SimpleSemaphore mutex3;
- private static SimpleSemaphore semaforo1;
- private static int[] datos = new int[N_DATOS];
- private static int[] resultados = new int[nPares];
- private volatile static int totalSumados = 0;
- private volatile static int posResultados = 0;
- private volatile static boolean terminado = false;
- private static int suma(int a, int b) {
- sleepRandom(1000);
- return a + b;
- }
- private static void inicializaDatos() {
- for (int i = 0; i < N_DATOS; i++) {
- datos[i] = (int) (Math.random() * 11);
- }
- for(int i = 0;i < nPares;i++) {
- resultados[i] = -1;
- }
- println("Los datos a sumar son: " + Arrays.toString(datos));
- }
- private static boolean estanSumados(boolean[] a) {
- for (boolean value : a) {
- if (!value)
- return false;
- }
- return true;
- }
- private static void sumador() {
- while(!terminado) {
- mutex1.acquire();
- int a = datos[totalSumados*2];
- int b = datos[totalSumados*2 + 1];
- totalSumados++;
- mutex1.release();
- int res = suma(a,b);
- mutex2.acquire();
- resultados[posResultados] = res;
- posResultados++;
- mutex2.release();
- if(totalSumados == nPares-1) {
- mutex3.acquire();
- procesosEnEspera++;
- if(procesosEnEspera < N_PROCESOS) {
- mutex3.release();
- semaforo1.acquire();
- } else {
- mutex3.release();
- for(int i = 0;i < nPares * 2;i++) {
- if(i < nPares) {
- datos[i] = resultados[i];
- } else {
- datos[i] = -1;
- }
- } // copia un array a otro y lo limpia
- nPares/=2;
- totalSumados = 0;
- posResultados = 0;
- for(int i = 0;i < N_PROCESOS;i++) {
- semaforo1.release();
- }
- }
- }
- }
- }
- public static void main(String[] args) {
- mutex1 = new SimpleSemaphore(1);
- mutex2 = new SimpleSemaphore(1);
- mutex3 = new SimpleSemaphore(1);
- semaforo1 = new SimpleSemaphore(0);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement