1
0
mirror of https://github.com/danog/amp.git synced 2024-11-27 04:24:42 +01:00

Implement TaskScheduler and first example using ext-task

This commit is contained in:
Niklas Keller 2018-07-10 20:22:09 +02:00
parent 205d37d849
commit ca5c961384
4 changed files with 61 additions and 16 deletions

View File

@ -40,7 +40,8 @@
"react/promise": "^2",
"friendsofphp/php-cs-fixer": "^2.3",
"phpunit/phpunit": "^6.0.9",
"phpstan/phpstan": "^0.8.5"
"phpstan/phpstan": "^0.8.5",
"concurrent-php/task": "1.0"
},
"autoload": {
"psr-4": {
@ -73,5 +74,19 @@
"scripts": {
"test": "@php -dzend.assertions=1 -dassert.exception=1 ./vendor/bin/phpunit",
"code-style": "@php ./vendor/bin/php-cs-fixer fix"
}
},
"repositories": [
{
"type": "package",
"package": {
"name": "concurrent-php/task",
"version": "1.0",
"source": {
"url": "https://github.com/concurrent-php/task",
"type": "git",
"reference": "origin/master"
}
}
}
]
}

View File

@ -1,33 +1,27 @@
<?php
#!/usr/bin/env php
require __DIR__ . '/../../vendor/autoload.php';
use Amp\Delayed;
use Amp\Loop;
use function Amp\asyncCall;
use Concurrent\Task;
use function Amp\delay;
// Shows how two for loops are executed concurrently.
// Note that the first two items are printed _before_ the Loop::run()
// as they're executed immediately and do not register any timers or defers.
asyncCall(function () {
print "starting first task" . PHP_EOL;
Task::async(function () {
for ($i = 0; $i < 5; $i++) {
print "1 - " . $i . PHP_EOL;
yield new Delayed(1000);
delay(1000);
}
});
asyncCall(function () {
print "starting second task" . PHP_EOL;
Task::async(function () {
for ($i = 0; $i < 5; $i++) {
print "2 - " . $i . PHP_EOL;
yield new Delayed(400);
delay(1000);
}
});
print "-- before Loop::run()" . PHP_EOL;
Loop::run();
print "-- after Loop::run()" . PHP_EOL;

View File

@ -2,6 +2,30 @@
namespace Amp\Internal;
use Amp\Loop;
use Concurrent\TaskScheduler;
TaskScheduler::setDefaultScheduler(new class extends TaskScheduler
{
private $dispatch;
public function __construct()
{
$this->dispatch = \Closure::fromCallable([$this, 'dispatch']);
}
protected function activate()
{
// TODO: Try calling $this->dispatch() directly here
Loop::defer($this->dispatch);
}
protected function runLoop()
{
Loop::run();
}
});
/**
* Formats a stacktrace obtained via `debug_backtrace()`.
*

View File

@ -3,8 +3,20 @@
namespace Amp
{
use Concurrent\Awaitable;
use React\Promise\PromiseInterface as ReactPromise;
function delay(int $msDelay): Awaitable
{
$deferred = new \Concurrent\Deferred;
Loop::delay($msDelay, function () use ($deferred) {
$deferred->resolve();
});
return $deferred->awaitable();
}
/**
* Returns a new function that wraps $callback in a promise/coroutine-aware function that automatically runs
* Generators as coroutines. The returned function always returns a promise when invoked. Errors have to be handled