コード例 #1
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();
  }
コード例 #2
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();
  }
コード例 #3
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;
 }
コード例 #4
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().");
    }
  }
コード例 #5
0
 public void run() {
   while (true) {
     newInputSemaphore.release();
     if (terminated) break;
     process();
     newOutputSemaphore.take();
   }
 }
コード例 #6
0
 public void getReady() {
   try {
     ready.acquire();
     ready.release();
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
 }
コード例 #7
0
ファイル: Condition.java プロジェクト: ryanym/CS162
  /**
   * Atomically release the associated lock and go to sleep on this condition variable until another
   * thread wakes it using <tt>wake()</tt>. The current thread must hold the associated lock. The
   * thread will automatically reacquire the lock before <tt>sleep()</tt> returns.
   *
   * <p>This implementation uses semaphores to implement this, by allocating a semaphore for each
   * waiting thread. The waker will <tt>V()</tt> this semaphore, so thre is no chance the sleeper
   * will miss the wake-up, even though the lock is released before caling <tt>P()</tt>.
   */
  public void sleep() {
    Lib.assertTrue(conditionLock.isHeldByCurrentThread());

    Semaphore waiter = new Semaphore(0);
    waitQueue.add(waiter);

    conditionLock.release();
    waiter.P();
    conditionLock.acquire();
  }
コード例 #8
0
ファイル: ThreadTP6.java プロジェクト: HKervadec/tp4info
 public void run() {
   System.out.println("Coucou " + this.getName());
   try {
     sem.p();
     Thread.sleep(2000);
     System.out.println("Je suis dans la zone protégé " + this.getName());
     sem.v();
   } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   System.out.println("je suis sorti ! " + this.getName());
 }
コード例 #9
0
ファイル: ReadWrite.java プロジェクト: sjc247/semahphores
  public void run() {
    pr.println("Writer " + id + " is trying to write");
    S.semWait(); // semWait on S, see if allowed in critical section
    pr.println("Writer " + id + " is starting to write");

    try {
      sleep((long) (Math.random() * 1000)); // "writing"
    } catch (InterruptedException e) {
    }
    ;
    pr.println("Writer " + id + " is done writing");

    S.semSignal(); // semSignal on S, done writing critical section
    pr.println("Writer " + id + " is wrapping things up");
  }
コード例 #10
0
 public boolean waitTillNotified(long millisecondsToWait) {
   try {
     return notificationSemaphore.tryAcquire(millisecondsToWait, TimeUnit.MILLISECONDS);
   } catch (InterruptedException e) {
     return false;
   }
 }
コード例 #11
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();
   }
 }
コード例 #12
0
 @Override
 public Message get(_Consommateur arg0) throws Exception, InterruptedException {
   Message m;
   consoLibre.p(); // on verifie la presence de ressources
   mutex.p(); // acce unique au buffer
   m = msg[debut];
   obs.retraitMessage(arg0, m);
   obstest.retraitMessage(arg0, m);
   debut = (debut + 1) % taille();
   cpt--;
   if (affichage == 1) {
     System.out.println("\tRecuperation IDCons " + arg0.identification() + " : " + m);
   }
   mutex.v(); // deblocage de l'acce au buffer
   prodLibre.v(); // pour avertir les producteurs
   return m;
 }
コード例 #13
0
 public void run() {
   buffer.init();
   ready.release();
   for (int i = 0; i < 100; i++) {
     buffer.put(i);
   }
   buffer.finish();
 }
コード例 #14
0
  public boolean offer(Object x, long msecs) throws InterruptedException {

    // Same as put, but with a timed wait for takers

    if (!unclaimedTakers_.attempt(msecs)) return false;

    doPut(x);
    return true;
  }
コード例 #15
0
 public void activate() {
   active = true;
   microphone.flush();
   speaker.flush();
   speaker.start();
   blocker.release();
   microphone.start();
   microphone.flush();
 }
コード例 #16
0
ファイル: Matcher.java プロジェクト: mustafatop/WORKSPACE
 public void run() {
   while (true) {
     matcher_wait.P();
     try {
       System.out.println("Matcher => run() metodu...");
       runMatcher();
     } catch (Exception e) {
       System.out.println("Matcher calisirken hata olustu!");
     }
   }
 }
コード例 #17
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();
    }
  }
コード例 #18
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;
 }
コード例 #19
0
ファイル: Lock.java プロジェクト: anujmnit71/testdandanciu
  public void acquire(XThread requester) {
    if (logger.isDebugEnabled()) {
      logger.debug("acquire::" + name + "(XThread) - start");
    }

    sem.P(requester);
    owner = requester;

    if (logger.isDebugEnabled()) {
      logger.debug("acquire::" + name + "(XThread) - end");
    }
  }
コード例 #20
0
 @Override
 public void put(_Producteur arg0, Message arg1) throws Exception, InterruptedException {
   prodLibre.p();
   mutex.p(); // blocage du buffer
   msg[fin] = arg1;
   obs.depotMessage(arg0, arg1);
   obstest.depotMessage(arg0, arg1);
   fin = (fin + 1) % taille();
   cpt++;
   if (!(((Producteur) arg0).check())) {
     TestProdCons.producteurAlive--;
     if (affichage == 1) {
       System.out.println("producteurAlive : " + TestProdCons.producteurAlive);
     }
   }
   if (affichage == 1) {
     System.out.println("\tDepot : " + arg1);
   }
   mutex.v(); // deblocage du buffer
   consoLibre.v(); // pour avertir les consommateurs
 }
コード例 #21
0
ファイル: ReadWrite.java プロジェクト: sjc247/semahphores
  public void run() {

    pr.println("Reader " + id + " trying to get into CR");

    mutex.semWait(); // semWait on mutex, only one reader can adjust count
    readCount++;

    if (readCount == 1) S.semWait(); // semWait on S

    mutex.semSignal(); // semSignal on mutex

    pr.println("Reader " + id + " is reading");

    try {
      sleep((long) (Math.random() * 1000));

    } catch (InterruptedException e) {
    }
    ;

    pr.println("Reader " + id + " is done reading");
    mutex.semWait();
    readCount--;
    if (readCount == 0) S.semSignal(); // semSignal on S
    mutex.semSignal(); // semSignal on mutex
  }
コード例 #22
0
ファイル: Lock.java プロジェクト: anujmnit71/testdandanciu
  public void release(XThread requester) {
    if (logger.isDebugEnabled()) {
      logger.debug("release::" + name + "(XThread) - start");
    }

    assert (requester == owner);
    owner = null;
    sem.V();

    if (logger.isDebugEnabled()) {
      logger.debug("release::" + name + "(XThread) - end");
    }
  }
コード例 #23
0
ファイル: PooledFatPipe.java プロジェクト: ioworks/fat-pipe
 @Override
 @SuppressWarnings({"unchecked"})
 public void shutdown(long time, TimeUnit unit) {
   started = false;
   try {
     lock.tryAcquire(time, unit);
   } catch (InterruptedException e) {
     logger.warn("shutdown", e);
   }
   if (group != null) group.interrupt();
   consumers = new Consumer[0];
   consumerSeqs = new long[0];
   outUse = new AtomicLongArray(0);
   executor.shutdown();
 }
コード例 #24
0
  public void put(Object x) throws InterruptedException {

    /*
      Basic protocol is:
      1. Wait until a taker arrives (via unclaimedTakers_ semaphore)
      2. Wait until no other puts are active (via onePut_)
      3. Insert the item, and signal taker that it is ready
         (via itemAvailable_ semaphore).
      4. Wait for item to be taken (via itemTaken_ semaphore).
      5. Allow another put to insert item (by releasing onePut_).

      Backouts due to interrupts or (for offer) timeouts are allowed
      only during the wait for takers. Upon claiming a taker, puts
      are forced to proceed, ignoring interrupts.
    */

    unclaimedTakers_.acquire();
    doPut(x);
  }
コード例 #25
0
ファイル: TaskManager.java プロジェクト: venks06/Nachos
  /**
   * Called by the parent thread to process work requests posted for it. This method does not return
   * unless there are no further pending requests to be processed AND all child threads have
   * terminated. If there are no requests to be processed, but some child threads are still active,
   * then the parent thread will block within this method awaiting further requests (for example,
   * those that will eventually result from the termination of the currently active child threads).
   *
   * @throws IllegalStateException if the calling thread is not registered as the parent thread for
   *     this TaskManager.
   */
  public void processRequests() throws IllegalStateException {
    try {
      // Don't let any threads except Parent thread execute this method
      if (!NachosThread.currentThread().name.equals(mParentThreadName)) return;
      // Main thread waits till all requests have been served / all worker threads have been
      // finished
      while (true) {
        // Run the post doInBackground actions such as onCompletion and onCancellation
        for (Runnable response : mResponses) {
          response.run();
        }
        if (mResponses.size() == mThreadCounter) {
          break;
        } else {
          mSemaphoreForFirstThread.P();
        }
      }
    } catch (Exception ex) {

    }
  }
コード例 #26
0
 /** Provides the service routine for the DS polling thread. */
 private void task() {
   int safetyCounter = 0;
   while (m_thread_keepalive) {
     try {
       m_packetDataAvailableSem.takeForever();
       synchronized (this) {
         getData();
         m_enhancedIO.updateData();
         setData();
       }
       synchronized (m_dataSem) {
         m_dataSem.notifyAll();
       }
       if (++safetyCounter >= 5) {
         //               System.out.println("Checking safety");
         MotorSafetyHelper.checkMotors();
         safetyCounter = 0;
       }
     } catch (SemaphoreException ex) {
       //
     }
   }
 }
コード例 #27
0
ファイル: Matcher.java プロジェクト: mustafatop/WORKSPACE
  private void Match(Objective incomingObjective) {
    System.out.println("Matcher => Match() metodu...");
    ArrayList matchedBehaviours = new ArrayList();
    try {
      System.out.println("Content'te bir olay var!!!");
      FipaMessage fm = incomingObjective.getMessage();
      int msgNum = incomingObjective.getMessageNum();
      MatcherOntology mo = new MatcherOntology();
      matchedBehaviours = mo.getPlan(fm);
      int numTasks = matchedBehaviours.size();

      System.out.println("Matcher'ýn eþleþtirdiði plan sayýsý: " + numTasks);
      if (numTasks > 1) System.out.println("Birden fazla Behaviour ile eslestirildi.");
      else if (numTasks == 0)
        System.out.println("Objective, hicbir behaviour ile eslestirilemedi.");
      else {
        String matchedBehaviour = (String) matchedBehaviours.get(0);
        System.out.println(matchedBehaviour);
        Class c = Class.forName("test." + matchedBehaviour);
        System.out.println("Matcher Behaviour sinifi...");
        Behaviour Plan = (Behaviour) c.newInstance();

        BehaviourQCell behQCell = new BehaviourQCell(Plan, msgNum);

        if (this.setProvisions(incomingObjective, Plan)) { // mesajdaki
          // parametreler,
          // provisionlara
          // getirilecektir
          BehaviourQ.add(behQCell);
          scheduler_notify.V();
          System.out.println("Objective " + matchedBehaviour + " ile eslestirildi.");
        }
      }
    } catch (Exception e) {
      System.out.println("Failed: " + e);
    }
  }
コード例 #28
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();
  }
コード例 #29
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;
    }
  }
コード例 #30
0
 /**
  * This should be called whenever state has changed that might cause the agent to do something.
  */
 protected void stateChanged() {
   stateChange.release();
 }