Understanding ReactPHP Event Loop Ticks
<?php
namespace React\EventLoop;
/**
* A stream_select() based event-loop.
*/
class StreamSelectLoop implements LoopInterface
{
private $futureTickQueue;
// ...
public function __construct()
{
$this->futureTickQueue = new FutureTickQueue($this);
}
// ...
}
<?php
namespace React\EventLoop\Tick;
class FutureTickQueue
{
private $eventLoop;
private $queue;
// ...
/**
* Flush the callback queue.
*/
public function tick()
{
// Only invoke as many callbacks as were on the queue when tick() was called.
$count = $this->queue->count();
while ($count--) {
call_user_func(
$this->queue->dequeue(),
$this->eventLoop
);
}
}
// ...
}
<?php
namespace React\EventLoop;
/**
* A stream_select() based event-loop.
*/
class StreamSelectLoop implements LoopInterface
{
// ...
public function futureTick(callable $listener)
{
$this->futureTickQueue->add($listener);
}
// ...
}
<?php
$eventLoop = \React\EventLoop\Factory::create();
$eventLoop->futureTick(function() {
echo "Tick\n";
});
echo "Loop starts\n";
$eventLoop->run();
echo "Loop stops\n";
<?php
$string = "Tick!\n";
$eventLoop->futureTick(function() use($string) {
echo $string;
});
<?php
use React\EventLoop\LoopInterface;
$eventLoop = \React\EventLoop\Factory::create();
$callback = function (LoopInterface $eventLoop) use (&$callback) {
echo "Hello world\n";
$eventLoop->futureTick($callback);
};
$eventLoop->futureTick($callback);
$eventLoop->futureTick(function(LoopInterface $eventLoop){
$eventLoop->stop();
});
$eventLoop->run();
echo "Finished\n";
Order of Execution
<?php
$eventLoop = \React\EventLoop\Factory::create();
$writable = new \React\Stream\WritableResourceStream(fopen('php://stdout', 'w'), $eventLoop);
$writable->write("I\O");
$eventLoop->addTimer(0, function(){
echo "Timer\n";
});
$eventLoop->futureTick(function(){
echo "Future tick\n";
});
$eventLoop->run();
<?php
namespace React\EventLoop;
/**
* A stream_select() based event-loop.
*/
class StreamSelectLoop implements LoopInterface
{
// ...
public function run()
{
$this->running = true;
while ($this->running) {
$this->futureTickQueue->tick();
// timers
// streams activity
}
}
}
Comments
Post a Comment