コード例 #1
0
ファイル: Buffer.java プロジェクト: darkxemis/Procesos
  public void producir(Thread thr) throws InterruptedException {

    lleno.acquire();
    mutex.acquire();

    buffer[entrada] = 1;
    System.out.println("Hebraproductora: " + thr.getName() + " produce en posición: " + entrada);
    Productorconsumidor.mostrar.setText(
        Productorconsumidor.mostrar.getText() + "Productor produce " + "\n");
    entrada = (entrada + 1) % buffer.length;
    contador = contador + 1;

    System.out.println("Productor produce ");
    for (int i = 0; i < buffer.length; i++) {
      System.out.print("[" + buffer[i] + "]");
    }

    for (int i = 0; i < buffer.length; i++) {
      Productorconsumidor.mostrar.setText(
          Productorconsumidor.mostrar.getText() + "[" + buffer[i] + "]");
    }
    Productorconsumidor.mostrar.setText(Productorconsumidor.mostrar.getText() + "\n");
    System.out.print("\n");

    mutex.release();
    vacio.release();
  }
コード例 #2
0
ファイル: Buffer.java プロジェクト: darkxemis/Procesos
  public void consumir(Thread thr) throws InterruptedException {

    vacio.acquire();
    mutex.acquire();

    buffer[salida] = 0;
    System.out.println("Hebraconsumidora: " + thr.getName() + " consume en posición: " + salida);
    Productorconsumidor.mostrar.setText(
        Productorconsumidor.mostrar.getText() + "Productor consume " + "\n");
    salida = (salida + 1) % buffer.length;
    contador = contador - 1;
    System.out.println("Consumidor consume ");
    for (int i = 0; i < buffer.length; i++) {
      System.out.print("[" + buffer[i] + "]");
    }

    for (int i = 0; i < buffer.length; i++) {
      Productorconsumidor.mostrar.setText(
          Productorconsumidor.mostrar.getText() + "[" + buffer[i] + "]");
    }
    Productorconsumidor.mostrar.setText(Productorconsumidor.mostrar.getText() + "\n");
    System.out.print("\n");

    mutex.release();
    lleno.release();
  }
コード例 #3
0
  /**
   * Asynchronously runs the Proton {@link Reactor} accepting and sending messages. Any other call
   * to this method on this {@link AmqpsIotHubConnection} will block until the {@link Reactor}
   * terminates and this {@link AmqpsIotHubConnection} closes. Normally, this method should only be
   * called once by the {@link #open()} method until the {@link AmqpsIotHubConnection} has been
   * closed.
   *
   * @throws IOException if the {@link AmqpsIotHubConnectionBaseHandler} has not been initialized.
   * @throws InterruptedException if there is a problem acquiring the semaphore.
   */
  private synchronized void startReactorAsync() throws IOException, InterruptedException {
    // Acquire permit to continue execution of this method and spawn a new thread.
    reactorSemaphore.acquire();

    if (this.amqpsHandler != null) {
      this.reactor = Proton.reactor(this);

      new Thread(
              () -> {
                try {
                  reactor.run();

                  // Closing here should be okay. The reactor will only stop running if the
                  // connection is remotely
                  // or locally closed. The transport will attempt to receive/send a message and
                  // will get an exception
                  // causing it to create a new AmqpsIoTHubConnection.
                  close();

                  // Release the semaphore and make permit available allowing for the next reactor
                  // thread to spawn.
                  reactorSemaphore.release();
                } catch (Exception e) {
                  close();
                  reactorSemaphore.release();
                }
              })
          .start();
    } else {
      throw new IOException(
          "The Handler has not been initialized. Ensure that the AmqpsIotHubConnection is in an OPEN state by calling open().");
    }
  }
コード例 #4
0
ファイル: PooledFatPipe.java プロジェクト: ioworks/fat-pipe
 /**
  * @return if <0, then this pipe should be stopped. If ==0, it should not wait. If >0, if it
  *     should wait
  */
 int execute() {
   if (!lock.tryAcquire()) return 1; // currently being accessed
   Thread myThread = Thread.currentThread();
   int threadIndex = -1;
   for (int i = 0; i < threads.length; i++) {
     if (threads[i] == null) {
       threads[i] = myThread;
       threadIndex = i;
       break;
     }
     if (myThread != threads[i]) continue;
     threadIndex = i;
     break;
   }
   Signal signal;
   if (threadIndex < 0) {
     signal = dummySignal;
   } else {
     SignalImpl s = signals[threadIndex];
     s.threadIndex = threadIndex;
     s.signaled = false;
     signal = s;
   }
   boolean hasData;
   try {
     hasData = poll(signal, null);
   } finally {
     signal.signal();
     if (threadIndex < 0) lock.release();
   }
   return 0;
 }
コード例 #5
0
 public void getReady() {
   try {
     ready.acquire();
     ready.release();
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
コード例 #6
0
 public void run() {
   buffer.init();
   ready.release();
   for (int i = 0; i < 100; i++) {
     buffer.put(i);
   }
   buffer.finish();
 }
コード例 #7
0
 public void run() {
   while (true) {
     newInputSemaphore.release();
     if (terminated) break;
     process();
     newOutputSemaphore.take();
   }
 }
コード例 #8
0
 public void activate() {
   active = true;
   microphone.flush();
   speaker.flush();
   speaker.start();
   blocker.release();
   microphone.start();
   microphone.flush();
 }
コード例 #9
0
 public void submitTask(final Runnable command) throws InterruptedException {
   semaphore.acquire();
   try {
     exec.execute(
         new Runnable() {
           public void run() {
             try {
               command.run();
             } finally {
               semaphore.release();
             }
           }
         });
   } catch (RejectedExecutionException e) {
     semaphore.release();
   }
 }
コード例 #10
0
  protected void doPut(Object x) {
    synchronized (onePut_) {
      insert(x);
      itemAvailable_.release();

      // Must ignore interrupts while waiting for acknowledgement
      boolean wasInterrupted = false;

      for (; ; ) {
        try {
          itemTaken_.acquire();
          break;
        } catch (InterruptedException ex) {
          wasInterrupted = true;
        }
      }

      if (wasInterrupted) Thread.currentThread().interrupt();
    }
  }
コード例 #11
0
ファイル: PooledFatPipe.java プロジェクト: ioworks/fat-pipe
 @Override
 public boolean setConsumers(List<Consumer<S>> list, long time, TimeUnit unit)
     throws IllegalArgumentException {
   if (list == null) throw new IllegalArgumentException("consumer list is not set");
   for (Consumer<S> consumer : list) {
     if (consumer == null) throw new IllegalArgumentException("consumer is null");
   }
   try {
     if (!lock.tryAcquire(time, unit)) throw new IllegalArgumentException("can't lock producer");
   } catch (InterruptedException e) {
     return false;
   }
   try {
     return setConsumers(list);
   } catch (InterruptedException e) {
     logger.warn("setting consumer", e);
   } finally {
     lock.release();
   }
   return false;
 }
コード例 #12
0
ファイル: PooledFatPipe.java プロジェクト: ioworks/fat-pipe
  public void start() {
    inputs = new AtomicReferenceArray<>(0);
    outputs = inputs;
    freeReceptors = new CopyOnWriteArrayList<>();
    sequence = 0;
    finalSequence = 0;
    finalProduct = null;
    reuseReceptors = new ArrayList<>(0);
    executor = Executors.newSingleThreadExecutor();

    started = true;
    if (poolSize > 0) {
      group = new ThreadGroup("FatPipe");
      group.setMaxPriority(Thread.MAX_PRIORITY);
    }
    signals = new SignalImpl[ARBITARY_THREADS + poolSize];
    threads = new Thread[ARBITARY_THREADS + poolSize];
    startTime = System.currentTimeMillis();
    sleptTime = 0;
    toSleepTime = 0;

    for (int i = 0; i < poolSize; i++) {
      Thread t = new Thread(group, this, name + "-" + i);
      t.setDaemon(true);
      threads[i] = t;
      t.start();
      if (sleep == 0) t.setPriority(Thread.MAX_PRIORITY);
      else if (sleep < 0) t.setPriority(Thread.NORM_PRIORITY);
      else t.setPriority(Thread.MIN_PRIORITY);
    }
    for (int i = 0; i < signals.length; i++) {
      signals[i] = new SignalImpl(lock);
    }
    if (pool != null) pool.add(this);
    lock.release();
  }
コード例 #13
0
 public void pickup() {
   pickup.release();
 }
コード例 #14
0
 /**
  * This should be called whenever state has changed that might cause the agent to do something.
  */
 protected void stateChanged() {
   stateChange.release();
 }
コード例 #15
0
 public void resume() {
   pause.release();
   isPaused = false;
   stateChanged();
 }
コード例 #16
0
    /** @param f Future that finished. */
    private void signalTaskFinished(GridFuture<Object> f) {
      assert f != null;

      sem.release();
    }
コード例 #17
0
  protected Object doTake(boolean timed, long msecs) throws InterruptedException {

    /*
      Basic protocol is:
      1. Announce that a taker has arrived (via unclaimedTakers_ semaphore),
          so that a put can proceed.
      2. Wait until the item is put (via itemAvailable_ semaphore).
      3. Take the item, and signal the put (via itemTaken_ semaphore).

      Backouts due to interrupts or timeouts are allowed
      only during the wait for the item to be available. However,
      even here, if the put of an item we should get has already
      begun, we ignore the interrupt/timeout and proceed.

    */

    // Holds exceptions caught at times we cannot yet rethrow or reinterrupt
    InterruptedException interruption = null;

    // Records that a timeout or interrupt occurred while waiting for item
    boolean failed = false;

    // Announce that a taker is present
    unclaimedTakers_.release();

    // Wait for a put to insert an item.

    try {
      if (!timed) itemAvailable_.acquire();
      else if (!itemAvailable_.attempt(msecs)) failed = true;
    } catch (InterruptedException ex) {
      interruption = ex;
      failed = true;
    }

    //  Messy failure mechanics

    if (failed) {

      // On interrupt or timeout, loop until either we can back out or acquire.
      // One of these must succeed, although it may take
      // multiple tries due to re-interrupts

      for (; ; ) {

        // Contortion needed to avoid catching our own throw
        boolean backout = false;

        try {
          // try to deny that we ever arrived.
          backout = unclaimedTakers_.attempt(0);

          // Cannot back out because a put is active.
          // So retry the acquire.

          if (!backout && itemAvailable_.attempt(0)) break;
        } catch (InterruptedException e) {
          if (interruption == null) // keep first one if a re-interrupt
          interruption = e;
        }

        if (backout) {
          if (interruption != null) throw interruption;
          else // must have been timeout
          return null;
        }
      }
    }

    // At this point, there is surely an item waiting for us.
    // Take it, and signal the put

    Object x = extract();
    itemTaken_.release();

    // if we had to continue even though interrupted, reset status
    if (interruption != null) Thread.currentThread().interrupt();

    return x;
  }
コード例 #18
0
 public void waitUntilFinished() { // Runs in other thread!
   newOutputSemaphore.release();
 }
コード例 #19
0
 public void notifyAnyWaiters() {
   notificationSemaphore.release();
 }
コード例 #20
0
ファイル: Rendezvous.java プロジェクト: huluwa/z_zdal
  protected Object doRendezvous(Object x, boolean timed, long msecs)
      throws InterruptedException, TimeoutException, BrokenBarrierException {

    // rely on semaphore to throw interrupt on entry

    long startTime;

    if (timed) {
      startTime = System.currentTimeMillis();
      if (!entryGate_.attempt(msecs)) {
        throw new TimeoutException(msecs);
      }
    } else {
      startTime = 0;
      entryGate_.acquire();
    }

    synchronized (this) {
      Object y = null;

      int index = entries_++;
      slots_[index] = x;

      try {
        // last one in runs function and releases
        if (entries_ == parties_) {

          departures_ = entries_;
          notifyAll();

          try {
            if (!broken_ && rendezvousFunction_ != null)
              rendezvousFunction_.rendezvousFunction(slots_);
          } catch (RuntimeException ex) {
            broken_ = true;
          }

        } else {

          while (!broken_ && departures_ < 1) {
            long timeLeft = 0;
            if (timed) {
              timeLeft = msecs - (System.currentTimeMillis() - startTime);
              if (timeLeft <= 0) {
                broken_ = true;
                departures_ = entries_;
                notifyAll();
                throw new TimeoutException(msecs);
              }
            }

            try {
              wait(timeLeft);
            } catch (InterruptedException ex) {
              if (broken_ || departures_ > 0) { // interrupted after release
                Thread.currentThread().interrupt();
                break;
              } else {
                broken_ = true;
                departures_ = entries_;
                notifyAll();
                throw ex;
              }
            }
          }
        }

      } finally {

        y = slots_[index];

        // Last one out cleans up and allows next set of threads in
        if (--departures_ <= 0) {
          for (int i = 0; i < slots_.length; ++i) slots_[i] = null;
          entryGate_.release(entries_);
          entries_ = 0;
        }
      }

      // continue if no IE/TO throw
      if (broken_) throw new BrokenBarrierException(index);
      else return y;
    }
  }
コード例 #21
0
ファイル: DHTNATPuncherImpl.java プロジェクト: aprasa/oldwork
  protected void publishSupport() {
    DHTTransport transport = dht.getTransport();

    if (TESTING || !transport.isReachable()) {

      DHTTransportContact local_contact = transport.getLocalContact();

      // see if the rendezvous has failed and therefore we are required to find a new one

      boolean force =
          rendezvous_target != null
              && failed_rendezvous.containsKey(rendezvous_target.getAddress());

      if (rendezvous_local_contact != null && !force) {

        if (local_contact.getAddress().equals(rendezvous_local_contact.getAddress())) {

          // already running for the current local contact

          return;
        }
      }

      DHTTransportContact explicit =
          (DHTTransportContact) explicit_rendezvous_map.get(local_contact.getAddress());

      if (explicit != null) {

        try {
          pub_mon.enter();

          rendezvous_local_contact = local_contact;
          rendezvous_target = explicit;

          runRendezvous();

        } finally {

          pub_mon.exit();
        }
      } else {

        final DHTTransportContact[] new_rendezvous_target = {null};

        DHTTransportContact[] reachables = dht.getTransport().getReachableContacts();

        int reachables_tried = 0;
        int reachables_skipped = 0;

        final Semaphore sem = plugin_interface.getUtilities().getSemaphore();

        for (int i = 0; i < reachables.length; i++) {

          DHTTransportContact contact = reachables[i];

          try {
            pub_mon.enter();

            // see if we've found a good one yet

            if (new_rendezvous_target[0] != null) {

              break;
            }

            // skip any known bad ones

            if (failed_rendezvous.containsKey(contact.getAddress())) {

              reachables_skipped++;

              sem.release();

              continue;
            }
          } finally {

            pub_mon.exit();
          }

          if (i > 0) {

            try {
              Thread.sleep(1000);

            } catch (Throwable e) {

            }
          }

          reachables_tried++;

          contact.sendPing(
              new DHTTransportReplyHandlerAdapter() {
                public void pingReply(DHTTransportContact ok_contact) {
                  trace("Punch:" + ok_contact.getString() + " OK");

                  try {
                    pub_mon.enter();

                    if (new_rendezvous_target[0] == null) {

                      new_rendezvous_target[0] = ok_contact;
                    }
                  } finally {

                    pub_mon.exit();

                    sem.release();
                  }
                }

                public void failed(DHTTransportContact failed_contact, Throwable e) {
                  try {
                    trace("Punch:" + failed_contact.getString() + " Failed");

                  } finally {

                    sem.release();
                  }
                }
              });
        }

        for (int i = 0; i < reachables.length; i++) {

          sem.reserve();

          try {
            pub_mon.enter();

            if (new_rendezvous_target[0] != null) {

              rendezvous_target = new_rendezvous_target[0];
              rendezvous_local_contact = local_contact;

              log(
                  "Rendezvous found: "
                      + rendezvous_local_contact.getString()
                      + " -> "
                      + rendezvous_target.getString());

              runRendezvous();

              break;
            }
          } finally {

            pub_mon.exit();
          }
        }

        if (new_rendezvous_target[0] == null) {

          log(
              "No rendezvous found: candidates="
                  + reachables.length
                  + ",tried="
                  + reachables_tried
                  + ",skipped="
                  + reachables_skipped);

          try {
            pub_mon.enter();

            rendezvous_local_contact = null;
            rendezvous_target = null;

          } finally {

            pub_mon.exit();
          }
        }
      }
    } else {

      try {
        pub_mon.enter();

        rendezvous_local_contact = null;
        rendezvous_target = null;

      } finally {

        pub_mon.exit();
      }
    }
  }