當前位置: 首頁>>代碼示例>>PHP>>正文


PHP SplPriorityQueue::isEmpty方法代碼示例

本文整理匯總了PHP中SplPriorityQueue::isEmpty方法的典型用法代碼示例。如果您正苦於以下問題:PHP SplPriorityQueue::isEmpty方法的具體用法?PHP SplPriorityQueue::isEmpty怎麽用?PHP SplPriorityQueue::isEmpty使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在SplPriorityQueue的用法示例。


在下文中一共展示了SplPriorityQueue::isEmpty方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的PHP代碼示例。

示例1: __construct

    public function __construct()
    {
        $this->queue = new \SplPriorityQueue();

        $this->timer = Loop\periodic(1, function () {
            $time = time();
            while (!$this->queue->isEmpty()) {
                $key = $this->queue->top();

                if (isset($this->expire[$key])) {
                    if ($time <= $this->expire[$key]) {
                        break;
                    }

                    unset($this->data[$key], $this->expire[$key], $this->ttl[$key]);
                }

                $this->queue->extract();
            }

            if ($this->queue->isEmpty()) {
                $this->timer->stop();
            }
        });

        $this->timer->stop();
        $this->timer->unreference();
    }
開發者ID:Nik-ADA,項目名稱:concurrent,代碼行數:28,代碼來源:Environment.php

示例2: pop

 /**
  * @see QueueInterface::pop()
  */
 public function pop()
 {
     if (!$this->innerQueue->isEmpty()) {
         $eta = $this->innerQueue->top()->getEta();
         if (!$eta || $eta->getTimestamp() <= time()) {
             return $this->innerQueue->extract();
         }
     }
     return false;
 }
開發者ID:rybakit,項目名稱:taskqueue,代碼行數:13,代碼來源:InMemoryQueue.php

示例3: pop

 /**
  * {@inheritdoc}
  */
 public function pop()
 {
     if (!$this->queue->isEmpty()) {
         $this->queue->setExtractFlags(\SplPriorityQueue::EXTR_PRIORITY);
         $priority = $this->queue->top();
         if (time() + $priority[0] >= 0) {
             $this->queue->setExtractFlags(\SplPriorityQueue::EXTR_DATA);
             return $this->queue->extract();
         }
     }
     throw new NoItemAvailableException($this);
 }
開發者ID:rybakit,項目名稱:phive-queue,代碼行數:15,代碼來源:InMemoryQueue.php

示例4: pop

 /**
  * {@inheritdoc}
  */
 public function pop()
 {
     if ($this->queue->isEmpty()) {
         return;
     }
     $this->queue->setExtractFlags(\SplPriorityQueue::EXTR_PRIORITY);
     $priority = $this->queue->top();
     if (time() + $priority[0] >= 0) {
         $this->queue->setExtractFlags(\SplPriorityQueue::EXTR_DATA);
         return $this->queue->extract();
     }
 }
開發者ID:schedulee,項目名稱:queue,代碼行數:15,代碼來源:InMemoryQueue.php

示例5: loop

 /**
  * 主循環
  * @see Events\EventInterface::loop()
  */
 public function loop()
 {
     $e = null;
     while (1) {
         // 如果有信號,嘗試執行信號處理函數
         pcntl_signal_dispatch();
         $read = $this->_readFds;
         $write = $this->_writeFds;
         // 等待可讀或者可寫事件
         @stream_select($read, $write, $e, 0, $this->_selectTimeout);
         // 嘗試執行定時任務
         if (!$this->_scheduler->isEmpty()) {
             $this->tick();
         }
         // 這些描述符可讀,執行對應描述符的讀回調函數
         if ($read) {
             foreach ($read as $fd) {
                 $fd_key = (int) $fd;
                 if (isset($this->_allEvents[$fd_key][self::EV_READ])) {
                     call_user_func_array($this->_allEvents[$fd_key][self::EV_READ][0], array($this->_allEvents[$fd_key][self::EV_READ][1]));
                 }
             }
         }
         // 這些描述符可寫,執行對應描述符的寫回調函數
         if ($write) {
             foreach ($write as $fd) {
                 $fd_key = (int) $fd;
                 if (isset($this->_allEvents[$fd_key][self::EV_WRITE])) {
                     call_user_func_array($this->_allEvents[$fd_key][self::EV_WRITE][0], array($this->_allEvents[$fd_key][self::EV_WRITE][1]));
                 }
             }
         }
     }
 }
開發者ID:hduwzy,項目名稱:test,代碼行數:38,代碼來源:Select.php

示例6: tick

 /**
  * Executes any pending timers. Returns the number of timers executed.
  *
  * @return int
  *
  * @internal
  */
 public function tick() : int
 {
     $count = 0;
     $time = microtime(true);
     while (!$this->queue->isEmpty()) {
         list($timer, $timeout) = $this->queue->top();
         if (!$this->timers->contains($timer) || $timeout !== $this->timers[$timer]) {
             $this->queue->extract();
             // Timer was removed from queue.
             continue;
         }
         if ($this->timers[$timer] > $time) {
             // Timer at top of queue has not expired.
             return $count;
         }
         // Remove and execute timer. Replace timer if persistent.
         $this->queue->extract();
         if ($timer->isPeriodic()) {
             $timeout = $time + $timer->getInterval();
             $this->queue->insert([$timer, $timeout], -$timeout);
             $this->timers[$timer] = $timeout;
         } else {
             $this->timers->detach($timer);
         }
         // Execute the timer.
         $timer->call();
         ++$count;
     }
     return $count;
 }
開發者ID:viniciusferreira,項目名稱:icicle,代碼行數:37,代碼來源:TimerManager.php

示例7: loop

 /**
  * @see Events\EventInterface::loop()
  */
 public function loop()
 {
     $e = null;
     while (1) {
         // Calls signal handlers for pending signals
         pcntl_signal_dispatch();
         $read = $this->_readFds;
         $write = $this->_writeFds;
         // Waiting read/write/signal/timeout events.
         $ret = @stream_select($read, $write, $e, 0, $this->_selectTimeout);
         if (!$this->_scheduler->isEmpty()) {
             $this->tick();
         }
         if (!$ret) {
             continue;
         }
         foreach ($read as $fd) {
             $fd_key = (int) $fd;
             if (isset($this->_allEvents[$fd_key][self::EV_READ])) {
                 call_user_func_array($this->_allEvents[$fd_key][self::EV_READ][0], array($this->_allEvents[$fd_key][self::EV_READ][1]));
             }
         }
         foreach ($write as $fd) {
             $fd_key = (int) $fd;
             if (isset($this->_allEvents[$fd_key][self::EV_WRITE])) {
                 call_user_func_array($this->_allEvents[$fd_key][self::EV_WRITE][0], array($this->_allEvents[$fd_key][self::EV_WRITE][1]));
             }
         }
     }
 }
開發者ID:hackty,項目名稱:Workerman,代碼行數:33,代碼來源:Select.php

示例8: nextTimeout

 /**
  * Get the number of microseconds until the next timer watcher is due.
  * 
  * @return int or null when no timers are pending.
  */
 protected function nextTimeout()
 {
     $time = \microtime(true);
     while (!$this->scheduler->isEmpty()) {
         list($watcher, $scheduled) = $this->scheduler->top();
         if ($watcher->enabled && $watcher->scheduled === $scheduled) {
             return (int) \max(0, ($watcher->due - $time) * 1000000);
         }
     }
 }
開發者ID:koolkode,項目名稱:async,代碼行數:15,代碼來源:NativeLoop.php

示例9: find_path

/**
 * Поиск самого дешёвого пути между двумя локациями
 * Для поиска используется алгоритм Дейкстры
 *
 * @see http://www.sitepoint.com/data-structures-4/
 *
 * @param array  $data   Массив с локациями и ценой проезда между ними [][src, dst, cost]
 * @param string $source Название исходного пункта
 * @param string $target Название конечного пункта
 *
 * @return SplStack
 */
function find_path(array $data, $source, $target)
{
    $graph = build_graph($data);
    // массив лучших цен кратчайшего пути для каждой локации
    $best_cost = [];
    // массив предыдущих локаций для каждой локации
    $prev_loc = array();
    // очередь из необработанных локаций
    $queue = new SplPriorityQueue();
    foreach ($graph as $src => $dst) {
        $best_cost[$src] = INF;
        // изначальные значения цен бесконечны
        $prev_loc[$src] = null;
        // предыдущие локации неизвестны
        foreach ($dst as $name => $cost) {
            // используем цену как приоритет в очереди
            $queue->insert($name, $cost);
        }
    }
    // цена поездки в исходный пункт = 0
    $best_cost[$source] = 0;
    while (!$queue->isEmpty()) {
        // получаем минимальную цену
        $u = $queue->extract();
        if (empty($graph[$u])) {
            continue;
        }
        // обрабатываем доступные маршруты для локации
        foreach ($graph[$u] as $v => $cost) {
            // альтернативная цена для маршрута
            $alt = $best_cost[$u] + $cost;
            if ($alt < $best_cost[$v]) {
                // обновляем минимальную цену для локации
                $best_cost[$v] = $alt;
                // добавляем локацию в массив предыдущих локаций
                $prev_loc[$v] = $u;
            }
        }
    }
    // ищем дешёвый путь и складываем его в стек
    $stack = new SplStack();
    $u = $target;
    $final_cost = 0;
    // проходим в обратном порядке от пункта назначения к исходному пункту
    while (isset($prev_loc[$u]) && $prev_loc[$u]) {
        $stack->push($u);
        $final_cost += $graph[$u][$prev_loc[$u]];
        $u = $prev_loc[$u];
    }
    $stack->push($source);
    return [$stack, $final_cost];
}
開發者ID:nafigator,項目名稱:travel-calculator,代碼行數:64,代碼來源:index.php

示例10: compileRoutes

 /**
  * {@inheritdoc}
  */
 public final function compileRoutes(RouteCompiler $compiler, RoutingContext $context) : array
 {
     $parsed = new \SplPriorityQueue();
     foreach ($this->routes as $route) {
         foreach ($route->compile($compiler) as list($priority, $depth, $route, $regex, $mapping)) {
             $parsed->insert(\array_merge([$regex, $depth, $priority, $route], $mapping), $priority);
         }
     }
     $result = [];
     while (!$parsed->isEmpty()) {
         $result[] = $parsed->extract();
     }
     return $result;
 }
開發者ID:koolkode,項目名稱:k1,代碼行數:17,代碼來源:App.php

示例11: _shortestPath

 /**
  * Поиск кратчайшего пути
  * @see https://www.youtube.com/watch?v=UA6aV1XJCGg
  */
 private function _shortestPath()
 {
     while (!$this->_nodeQueue->isEmpty()) {
         $u = $this->_nodeQueue->extract();
         if (!empty($this->_routes[$u])) {
             foreach ($this->_routes[$u] as $v => $cost) {
                 $newCost = $this->_destinations[$u] + $cost;
                 if ($newCost < $this->_destinations[$v]) {
                     $this->_destinations[$v] = $newCost;
                     $this->_predecessors[$v] = $u;
                 }
             }
         }
     }
 }
開發者ID:Arbuzov,項目名稱:Travel,代碼行數:19,代碼來源:Route.php

示例12: findNeighbors

 private function findNeighbors($type, $keywords, $id)
 {
     $queue = new SplPriorityQueue();
     $queue->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
     $cursor = $this->m->websites->find([]);
     foreach ($cursor as $doc) {
         if ($doc['_id'] != new MongoId($id)) {
             $d = $this->distance($type, $keywords, $doc['type'], $doc['keywords']);
             $queue->insert($doc, $d);
         }
     }
     $res = [];
     for ($i = 0; $i < 20 && !$queue->isEmpty(); $i++) {
         $res[] = $queue->extract();
     }
     return $res;
 }
開發者ID:jbgtmartin,項目名稱:rich,代碼行數:17,代碼來源:Controller.php

示例13: getTimeout

 /**
  * @return int Milliseconds until next timer expires or -1 if there are no pending times.
  */
 private function getTimeout()
 {
     while (!$this->timerQueue->isEmpty()) {
         list($watcher, $expiration) = $this->timerQueue->top();
         $id = $watcher->id;
         if (!isset($this->timerExpires[$id]) || $expiration !== $this->timerExpires[$id]) {
             $this->timerQueue->extract();
             // Timer was removed from queue.
             continue;
         }
         $expiration -= (int) (\microtime(true) * self::MILLISEC_PER_SEC);
         if ($expiration < 0) {
             return 0;
         }
         return $expiration;
     }
     return -1;
 }
開發者ID:amphp,項目名稱:loop,代碼行數:21,代碼來源:NativeLoop.php

示例14: compileRoutes

 /**
  * {@inheritdoc}
  */
 public final function compileRoutes(RouteCompiler $compiler, RoutingContext $context) : array
 {
     $ref = new \ReflectionClass(static::class);
     $parsed = new \SplPriorityQueue();
     foreach ($ref->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
         if ($method->isStatic() || !$method->hasReturnType()) {
             continue;
         }
         $type = (string) $method->getReturnType();
         if ($type !== Route::class && !\is_subclass_of($type, Route::class)) {
             continue;
         }
         $args = $context->container->populateArguments($method, [], new InjectionPoint(static::class));
         $route = $this->{$method->name}(...$args);
         foreach ($route->compile($compiler) as list($priority, $depth, $route, $regex, $mapping)) {
             $parsed->insert(\array_merge([$regex, $depth, $priority, $route], $mapping), $priority);
         }
     }
     $result = [];
     while (!$parsed->isEmpty()) {
         $result[] = $parsed->extract();
     }
     return $result;
 }
開發者ID:koolkode,項目名稱:k1,代碼行數:27,代碼來源:Controller.php

示例15: tokenize

 public function tokenize(string $input) : array
 {
     if (!$this->initialized) {
         $this->initialized = true;
         $this->initialize();
     }
     $types = [];
     $parts = [];
     $transform = [];
     foreach ($this->tokens as $k => list($v, $t)) {
         $types[] = $k;
         $parts[] = '(' . $v . ')';
         $transform[] = $t;
     }
     $sorter = new \SplPriorityQueue();
     foreach ($this->terminals as $k => list(, $terminal)) {
         $sorter->insert([$k, $terminal], strlen($terminal));
     }
     while (!$sorter->isEmpty()) {
         list($k, $terminal) = $sorter->extract();
         $types[] = $k;
         $parts[] = '(' . $terminal . ')';
         $transform[] = NULL;
     }
     $types[] = 'T_IDENTIFIER';
     $parts[] = '(' . $this->identifierPattern . ')';
     $transform[] = NULL;
     $regex = "~" . implode('|', $parts) . "~AS";
     $len = strlen($input);
     $offset = 0;
     $tokens = [];
     $line = 1;
     $pos = 1;
     $m = NULL;
     while (true) {
         if ($offset >= $len) {
             break;
         }
         if (!preg_match($regex, $input, $m, NULL, $offset)) {
             throw new \RuntimeException(sprintf('No matching token found at position: "%s"', substr($input, $offset, 10)));
         }
         $i = count($m) - 2;
         $type = $types[$i];
         $tlen = strlen($m[0]);
         if ($type === 'T_IDENTIFIER') {
             $key = strtolower($m[0]);
             if (isset($this->keywords[$key])) {
                 $keyword = $this->keywords[$key];
                 if (!$keyword[1] || $m[0] == $keyword[2]) {
                     $type = $keyword[0];
                     $m[0] = $keyword[2];
                 }
             }
         }
         if (empty($this->skip[$type])) {
             $tokens[] = $this->createToken($type, isset($transform[$i]) ? $transform[$i]($m[0]) : $m[0], $line, $pos, $offset + 1);
         }
         $offset += $tlen;
         $pos += $tlen;
         if (false !== strpos($m[0], "\n")) {
             $line += substr_count($m[0], "\n");
             $pos = strlen(substr($m[0], strrpos($m[0], "\n"))) + 1;
         }
     }
     return $tokens;
 }
開發者ID:koolkode,項目名稱:parser,代碼行數:66,代碼來源:Lexer.php


注:本文中的SplPriorityQueue::isEmpty方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。