示例#1
1
 /**
  * Starts pending tasks end move them from the pendingQueue to the runningQueue
  */
 private function startPendingTasks()
 {
     while (count($this->runningTasks) < $this->concurrencyLimit && !$this->pendingTasks->isEmpty()) {
         /** @var TaskInterface $task */
         $task = $this->pendingTasks->dequeue();
         $task->start()->progress(function (Event $notification) {
             $this->deferred->notify($notification);
         })->always(function () use($task) {
             $this->finishedTasks[] = $task;
             $this->deferred->notify(new TaskFinishedEvent($this, $task));
         });
         $this->deferred->notify(new TaskStartedEvent($this, $task));
         $this->runningTasks->enqueue($task);
     }
 }
示例#2
0
 /**
  * @return LogEvent
  */
 public function getLoggedEvent() : LogEvent
 {
     if (!$this->hasLoggedEvents()) {
         throw new \LogicException('No more events logged!');
     }
     return $this->logs->dequeue();
 }
 public function onExit($status)
 {
     if ($this->pendingRequests->count() > 0) {
         $nextExpectedTest = $this->pendingRequests->dequeue();
         $this->distributor->testCompleted($this, TestResult::errorFromRequest($nextExpectedTest, "Worker{$this->id} died\n{$this->testErr}"));
     }
 }
示例#4
0
 /** @return Error|null */
 public static function pop()
 {
     if (!self::$errors) {
         return null;
     }
     return self::$errors->count() > 0 ? self::$errors->dequeue() : null;
 }
 /**
  * Deliver notifications via given instance of Notifier
  * @param Notifier $notifier
  */
 public function deliver(Notifier $notifier)
 {
     foreach ($this->queue as $notification) {
         $notifier->notify($notification);
         $this->queue->dequeue();
     }
 }
示例#6
0
文件: Next.php 项目: mrferos/GenieDi
 public function __invoke($id, $service)
 {
     if ($this->middlewares->isEmpty()) {
         return $service;
     }
     $method = $this->middlewares->dequeue();
     return call_user_func($method, $this->container, new Next($this->container, $this->middlewares), $id, $service);
 }
 public function close()
 {
     if (!$this->promises->isEmpty()) {
         $this->promises->dequeue()->resolve();
     } else {
         $this->current--;
     }
 }
 public function uncork()
 {
     if (!$this->corked) {
         return;
     }
     while (!$this->corked && !$this->writeBuffer->isEmpty()) {
         $this->doWrite(...$this->writeBuffer->dequeue());
     }
 }
示例#9
0
 /**
  * @inheritDoc
  */
 public function getQuery(Driver $driver, $link)
 {
     if (!$this->pool->contains($link)) {
         throw new \OutOfBoundsException(sprintf('Undefined %s in the pooling controller.', $driver->info($link)));
     }
     if (!$this->waiting->isEmpty()) {
         return $this->waiting->dequeue();
     }
     $this->idle->enqueue($link);
 }
示例#10
0
 protected function processQueue()
 {
     $this->loop->futureTick(function () {
         if ($this->callQueue->isEmpty()) {
             return;
         }
         $message = $this->callQueue->dequeue();
         $data = ['function' => $message->getFunction(), 'args' => $message->getArgs(), 'errorResultCode' => $message->getErrorResultCode()];
         $message->getDeferred()->resolve($data);
     });
 }
示例#11
0
 /**
  * Once a connection has finished being used...
  * @param Connection $connection
  */
 public function releaseConnection(Connection $connection)
 {
     // If we have any promises waiting for the connection, pass it along.
     if ($this->waiting->count() > 0) {
         $cb = $this->waiting->dequeue();
         $cb($connection);
         return;
     }
     // Otherwise, move it to the idle queue.
     $this->available->enqueue($connection);
 }
示例#12
0
 /**
  * @param Message $chapterCommand
  * @param mixed $data
  * @param ChapterLogger $chapterLogger
  */
 public function __invoke(Message $chapterCommand, $data, ChapterLogger $chapterLogger)
 {
     $done = $this->done;
     // No middleware remains; done
     if ($this->queue->isEmpty()) {
         return $done($chapterCommand, $data, $chapterLogger);
     }
     $stage = $this->queue->dequeue();
     $executeStage = $this->executeStage;
     return $executeStage($stage, $chapterCommand, $data, $chapterLogger, $this);
 }
示例#13
0
 private function run()
 {
     /** @var HttpServer $server */
     $server = $this->container->get('http_server');
     // Run async dispatcher
     $server->getLoop()->addPeriodicTimer(Timer::MIN_INTERVAL, function (Timer $timer) {
         if ($this->queue->isEmpty()) {
             $timer->cancel();
             return;
         }
         $event = $this->queue->dequeue();
         $this->dispatch($event);
     });
 }
示例#14
0
 /**
  * @param Request $request
  * @param Response $response
  * @param callable[] ...$callables unshift callables (top priority)
  * @return Response
  */
 public function __invoke(Request $request, Response $response, ...$callables)
 {
     while ($callable = array_pop($callables)) {
         $this->queue->unshift($callable);
     }
     if ($this->queue->isEmpty()) {
         return $response;
     }
     $callable = $this->resolve($this->queue->dequeue());
     if (is_callable($callable)) {
         return call_user_func($callable, $request, $response, $this);
     } else {
         throw new \UnexpectedValueException();
     }
 }
示例#15
0
 /**
  * Process the given queue of template files and
  * returns the generated output.
  *
  * @param string $file
  *
  * @return string
  * @throws RendererException
  */
 public function render(string $file) : string
 {
     if ($this->rendering) {
         throw new RendererException("Cannot call render() inside templates.");
     }
     $this->rendering = true;
     $this->queue->enqueue($file);
     $this->sections()->declare('content');
     ob_start();
     while (!$this->queue->isEmpty()) {
         $file = $this->engine->path($this->queue->dequeue());
         if (!file_exists($file)) {
             throw new \RuntimeException("Cannot find file: {$file}");
         }
         require $file;
         $this->sections()->populate('content', ob_get_contents(), 'replace');
         ob_clean();
         if ($this->extended) {
             $this->extended = false;
         }
     }
     ob_end_clean();
     $this->rendering = false;
     return $this->sections()->fetch('content');
 }
示例#16
0
 /**
  * @return string[] names of any dependencies involved in dependency cycle[s] (or that depend
  *     upon those in the cycle)
  */
 public function list_dependency_cycles()
 {
     $dep_counts = $this->dependency_counts();
     $depends_on = $this->reverse_graph();
     $deps_met_queue = new \SplQueue();
     foreach ($dep_counts as $dependency => $count) {
         if ($count === 0) {
             $deps_met_queue->enqueue($dependency);
         }
     }
     // Iteratively resolve dependencies
     $num_removed = 0;
     while (!$deps_met_queue->isEmpty()) {
         $name = $deps_met_queue->dequeue();
         $num_removed++;
         if (!array_key_exists($name, $depends_on)) {
             continue;
         }
         foreach ($depends_on[$name] as $dependant) {
             $dep_counts[$dependant]--;
             if ($dep_counts[$dependant] === 0) {
                 $deps_met_queue->enqueue($dependant);
             }
         }
     }
     // Find the dependencies that couldn't be resolved
     $depends_on_cycle = [];
     foreach ($dep_counts as $dependency => $count) {
         if ($count > 0) {
             $depends_on_cycle[] = $dependency;
         }
     }
     return $depends_on_cycle;
 }
示例#17
0
 /**
  * a generator that loops once over the dequeued and return a watcher
  *
  * @return WatcherInterface[]
  */
 protected function getDequeuedWatcher()
 {
     $c = $this->queue->count();
     for ($i = 0; $i < $c; $i++) {
         (yield $this->queue->dequeue());
     }
 }
示例#18
0
 /**
  * @param null $lastPublicationId
  */
 private function processStateQueue($lastPublicationId = null)
 {
     if ($lastPublicationId !== null) {
         // create an array of pub ids
         // if we can't find the lastPublicationId in the queue
         // then we are going to assume it was before our time
         $pubIds = [];
         /** @var EventMessage $msg */
         foreach ($this->pauseQueue as $msg) {
             $pubIds[] = $msg->getPublicationId();
         }
         if (!in_array($lastPublicationId, $pubIds)) {
             $lastPublicationId = null;
         }
     }
     while (!$this->pauseQueue->isEmpty()) {
         $msg = $this->pauseQueue->dequeue();
         if ($lastPublicationId === null) {
             $this->sendEventMessage($msg);
         }
         if ($lastPublicationId == $msg->getPublicationId()) {
             $lastPublicationId = null;
         }
     }
 }
示例#19
0
文件: bfs.php 项目: keevitaja/bfs-php
function bfs_path($graph, $start, $end)
{
    $queue = new SplQueue();
    # Enqueue the path
    $queue->enqueue([$start]);
    $visited = [$start];
    while ($queue->count() > 0) {
        $path = $queue->dequeue();
        # Get the last node on the path
        # so we can check if we're at the end
        $node = $path[sizeof($path) - 1];
        if ($node === $end) {
            return $path;
        }
        foreach ($graph[$node] as $neighbour) {
            if (!in_array($neighbour, $visited)) {
                $visited[] = $neighbour;
                # Build new path appending the neighbour then and enqueue it
                $new_path = $path;
                $new_path[] = $neighbour;
                $queue->enqueue($new_path);
            }
        }
    }
    return false;
}
示例#20
0
 /**
  * Process the Queue
  *
  * @throws \Exception
  */
 public function processQueue()
 {
     if (!$this->getAllowMultipleRegistrations()) {
         throw new \Exception("queuing only allowed when there are multiple registrations");
     }
     // find the best candidate
     while ($this->callQueue->count() > 0) {
         $congestion = true;
         /* @var $bestRegistration \Thruway\Registration */
         $bestRegistration = $this->registrations[0];
         /* @var $registration \Thruway\Registration */
         foreach ($this->registrations as $registration) {
             if ($registration->getSession()->getPendingCallCount() == 0) {
                 $bestRegistration = $registration;
                 $congestion = false;
                 break;
             }
             if ($registration->getSession()->getPendingCallCount() < $bestRegistration->getSession()->getPendingCallCount()) {
                 $bestRegistration = $registration;
             }
         }
         if ($congestion) {
             // there is congestion
             $bestRegistration->getSession()->getRealm()->publishMeta('thruway.metaevent.procedure.congestion', [["name" => $this->getProcedureName()]]);
             return;
         }
         $call = $this->callQueue->dequeue();
         $bestRegistration->processCall($call);
     }
 }
示例#21
0
 protected function doTask()
 {
     $resource = null;
     //从空闲队列中取出可用的资源
     while (count($this->idlePool) > 0) {
         $_resource = $this->idlePool->dequeue();
         $rid = spl_object_hash($_resource);
         //资源已经不可用了,连接已关闭
         if (!isset($this->resourcePool[$rid])) {
             continue;
         } else {
             //找到可用连接
             $resource = $_resource;
             break;
         }
     }
     //没有可用连接,继续等待
     if (!$resource) {
         if (count($this->resourcePool) == 0) {
             call_user_func($this->createFunction);
             $this->resourceNum++;
         }
         return;
     }
     $callback = $this->taskQueue->dequeue();
     call_user_func($callback, $resource);
 }
 /**
  * Close the writer
  *
  * @return void
  */
 public function shutdown()
 {
     while (!$this->buffer->isEmpty()) {
         $this->buffer->dequeue();
     }
     $this->writer->shutdown();
 }
示例#23
0
 public function processQueue()
 {
     if ($this->commandQueue->count() == 0) {
         return;
     }
     if ($this->connStatus === $this::CONNECTION_BAD) {
         $this->failAllCommandsWith(new \Exception("Bad connection: " . $this->lastError));
         $this->stream->end();
         return;
     }
     while ($this->commandQueue->count() > 0 && $this->queryState === static::STATE_READY) {
         /** @var CommandInterface $c */
         $c = $this->commandQueue->dequeue();
         $this->debug("Sending " . get_class($c));
         if ($c instanceof Query) {
             $this->debug("Sending simple query: " . $c->getQueryString());
         }
         $this->stream->write($c->encodedMessage());
         if ($c instanceof Terminate) {
             $this->stream->end();
         }
         if ($c->shouldWaitForComplete()) {
             $this->queryState = $this::STATE_BUSY;
             if ($c instanceof Query) {
                 $this->queryType = $this::QUERY_SIMPLE;
             } elseif ($c instanceof Sync) {
                 $this->queryType = $this::QUERY_EXTENDED;
             }
             $this->currentCommand = $c;
             return;
         }
     }
 }
示例#24
0
 /**
  * Receive a value from the channel.
  * 
  * Be careful when you may receive null values: you need to change the EOF param accordingly!
  * 
  * @param mixed $eof The EOF value, a channel will return this value if it has been closed without an error.
  * @return mixed The received value.
  * 
  * @throws \Throwable Fails if the channel has been closed with an error.
  */
 public function receive($eof = null) : Awaitable
 {
     if (!$this->buffer) {
         while ($this->senders && !$this->senders->isEmpty()) {
             $subscription = $this->senders->dequeue();
             if ($subscription->active) {
                 $subscription->resolve($subscription->data);
                 return new Success($subscription->data);
             }
         }
     } elseif (!$this->buffer->isEmpty()) {
         while ($this->senders && !$this->senders->isEmpty()) {
             $subscription = $this->senders->dequeue();
             if ($subscription->active) {
                 $subscription->resolve($subscription->data);
                 $this->buffer->push($subscription->data);
             }
         }
         return new Success($this->buffer->dequeue());
     }
     if ($this->closed instanceof \Throwable) {
         return new Failure($this->closed);
     } elseif ($this->closed) {
         return new Success($eof);
     }
     if (!$this->receivers) {
         $this->receivers = new \SplQueue();
     }
     $this->receivers->enqueue($subscription = new ChannelSubscription($eof));
     return $subscription;
 }
示例#25
0
 protected function render(Func $func)
 {
     if (null !== $func->cfg) {
         $this->enqueueBlock($func->cfg);
     }
     $renderedOps = new \SplObjectStorage();
     $renderedBlocks = new \SplObjectStorage();
     while ($this->blockQueue->count() > 0) {
         $block = $this->blockQueue->dequeue();
         $ops = [];
         if ($block === $func->cfg) {
             foreach ($func->params as $param) {
                 $renderedOps[$param] = $ops[] = $this->renderOp($param);
             }
         }
         foreach ($block->phi as $phi) {
             $result = $this->indent($this->renderOperand($phi->result) . " = Phi(");
             $result .= implode(', ', array_map([$this, 'renderOperand'], $phi->vars));
             $result .= ')';
             $renderedOps[$phi] = $ops[] = ["op" => $phi, "label" => $result, "childBlocks" => []];
         }
         foreach ($block->children as $child) {
             $renderedOps[$child] = $ops[] = $this->renderOp($child);
         }
         $renderedBlocks[$block] = $ops;
     }
     $varIds = $this->varIds;
     $blockIds = $this->blocks;
     $this->reset();
     return ["blocks" => $renderedBlocks, "ops" => $renderedOps, "varIds" => $varIds, "blockIds" => $blockIds];
 }
示例#26
0
 /**
  * {@inheritdoc}
  */
 protected function executePipeline(ConnectionInterface $connection, \SplQueue $commands)
 {
     while (!$commands->isEmpty()) {
         $connection->writeRequest($commands->dequeue());
     }
     $connection->disconnect();
     return array();
 }
示例#27
0
 /**
  * {@inheritdoc}
  */
 public function tick()
 {
     if (!$this->process->isRunning() && $this->outputBuffer->isEmpty()) {
         usleep(1000);
         if ($this->outputBuffer->isEmpty()) {
             if ($this->process->isSuccessful()) {
                 $this->deferred->resolve(new MessageEvent($this, $this->process->getOutput()));
             } else {
                 $this->deferred->reject(new MessageEvent($this, $this->process->getOutput()));
             }
             return;
         }
     }
     if (!$this->outputBuffer->isEmpty()) {
         $this->deferred->notify(new MessageEvent($this, $this->outputBuffer->dequeue()[1]));
     }
 }
示例#28
0
 /**
  * Cancels all pending tasks.
  */
 private function cancelPending()
 {
     if (!$this->busyQueue->isEmpty()) {
         $exception = new WorkerException('Worker was shut down.');
         do {
             $this->busyQueue->dequeue()->cancel($exception);
         } while (!$this->busyQueue->isEmpty());
     }
 }
示例#29
0
 /**
  * 
  * @throws Exception
  * @return int
  */
 protected function _getNewStreamId()
 {
     if ($this->_lastStreamId < 32767) {
         return ++$this->_lastStreamId;
     }
     while ($this->_recycledStreams->isEmpty()) {
         $this->_getResponse();
     }
     return $this->_recycledStreams->dequeue();
 }
示例#30
0
 public function execute()
 {
     /** @var Transaction[] */
     $failed = [];
     while (!$this->transactionsToRetry->isEmpty()) {
         //Some failed transactions are waiting from the previous execution to be retried
         $this->transactionQueue->enqueue($this->transactionsToRetry->dequeue());
     }
     if (!$this->transactionQueue->isEmpty()) {
         $this->player->getServer()->getPluginManager()->callEvent($ev = new InventoryTransactionEvent($this));
     } else {
         return;
     }
     while (!$this->transactionQueue->isEmpty()) {
         $transaction = $this->transactionQueue->dequeue();
         if ($ev->isCancelled()) {
             $this->transactionCount -= 1;
             $transaction->sendSlotUpdate($this->player);
             //Send update back to client for cancelled transaction
             unset($this->inventories[spl_object_hash($transaction)]);
             continue;
         } elseif (!$transaction->execute($this->player)) {
             $transaction->addFailure();
             if ($transaction->getFailures() >= self::DEFAULT_ALLOWED_RETRIES) {
                 /* Transaction failed completely after several retries, hold onto it to send a slot update */
                 $this->transactionCount -= 1;
                 $failed[] = $transaction;
             } else {
                 /* Add the transaction to the back of the queue to be retried on the next tick */
                 $this->transactionsToRetry->enqueue($transaction);
             }
             continue;
         }
         $this->transactionCount -= 1;
         $transaction->setSuccess();
         $transaction->sendSlotUpdate($this->player);
         unset($this->inventories[spl_object_hash($transaction)]);
     }
     foreach ($failed as $f) {
         $f->sendSlotUpdate($this->player);
         unset($this->inventories[spl_object_hash($f)]);
     }
 }