Re: Why PHP 7 yield from still single thread and blocking thread?
| From: | Niklas Keller | Date: | Mon, 07 Dec 2015 10:24:18 +0000 |
| Subject: | Re: Why PHP 7 yield from still single thread and blocking thread? | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-89694@lists.php.net to get a copy of this message | ||
Hi Netroby,
> I wrote a small test. to see if it really concurrent processing any tasks.
> the result looks bad. Still single blocking thread.
>
As the RFC already states:
The actual implementation of coroutine task schedulers is outside the scope
> of this document. This RFC focuses only on the language-level machinery
> needed to make such tools more feasible in userland. It should be obvious
> that simply moving code into a generator function will not somehow make it
> magically concurrent.
You need a task scheduler like Amp (https://github.com/amphp/amp).
With Amp, you code would look like:
<?php
>
> function delayYield() {
> $delay = mt_rand(1, 5);
> echo "Delay $delay seconds" . PHP_EOL;
> yield new Amp\Pause($delay * 1000); // <-- Note: It's not using a
> synchrnous sleep here!
> return date('Y-m-d H:i:s');
> }
>
> Amp\run(function() {
>
$promises = [];
>
for ($i = 0; $i < 3; $i++) {
> $promises[] = Amp\resolve(delayYield()); // turns the generator
> into a promise so they're combinable with Amp\all
> }
>
$dates = yield Amp\all($promises);
>
});
>
yield from is more to factor larger functions into smaller units than
directly for doing tasks asynchronously.
Regards, Niklas