当前位置: 首页>>代码示例>>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;未经允许,请勿转载。