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(); }
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(); }
/** * @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; }
/** * 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()."); } }
public void run() { while (true) { newInputSemaphore.release(); if (terminated) break; process(); newOutputSemaphore.take(); } }
public void getReady() { try { ready.acquire(); ready.release(); } catch (InterruptedException e) { e.printStackTrace(); } }
/** * 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(); }
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()); }
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"); }
public boolean waitTillNotified(long millisecondsToWait) { try { return notificationSemaphore.tryAcquire(millisecondsToWait, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { return false; } }
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(); } }
@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; }
public void run() { buffer.init(); ready.release(); for (int i = 0; i < 100; i++) { buffer.put(i); } buffer.finish(); }
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; }
public void activate() { active = true; microphone.flush(); speaker.flush(); speaker.start(); blocker.release(); microphone.start(); microphone.flush(); }
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!"); } } }
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(); } }
@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; }
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"); } }
@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 }
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 }
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"); } }
@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(); }
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); }
/** * 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) { } }
/** 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) { // } } }
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); } }
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(); }
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; } }
/** * This should be called whenever state has changed that might cause the agent to do something. */ protected void stateChanged() { stateChange.release(); }