1
0
mirror of https://github.com/danog/parallel.git synced 2024-12-02 09:37:57 +01:00
parallel/examples/thread.php

46 lines
1.3 KiB
PHP
Raw Permalink Normal View History

2015-08-07 01:59:25 +02:00
#!/usr/bin/env php
2015-07-14 00:30:59 +02:00
<?php
2018-10-07 16:50:45 +02:00
require \dirname(__DIR__).'/vendor/autoload.php';
2015-07-14 00:30:59 +02:00
2017-06-17 18:31:35 +02:00
use Amp\Delayed;
2017-05-18 09:51:31 +02:00
use Amp\Loop;
2017-11-30 03:17:49 +01:00
use Amp\Parallel\Context\Thread;
use Amp\Parallel\Sync\Channel;
2016-08-18 18:04:48 +02:00
Loop::run(function () {
$timer = Loop::repeat(1000, function () {
2016-08-18 18:04:48 +02:00
static $i;
$i = $i ? ++$i : 1;
print "Demonstrating how alive the parent is for the {$i}th time.\n";
});
2017-05-18 09:51:31 +02:00
2016-08-18 18:04:48 +02:00
try {
// Create a new child thread that does some blocking stuff.
2018-10-21 17:34:08 +02:00
$context = yield Thread::run(function (Channel $channel): \Generator {
2018-10-07 16:50:45 +02:00
\printf("Received the following from parent: %s\n", yield $channel->receive());
2017-05-18 09:51:31 +02:00
2016-08-18 18:04:48 +02:00
print "Sleeping for 3 seconds...\n";
2018-10-07 16:50:45 +02:00
\sleep(3); // Blocking call in thread.
2017-05-18 09:51:31 +02:00
yield $channel->send("Data sent from child.");
2017-05-18 09:51:31 +02:00
2016-08-18 18:04:48 +02:00
print "Sleeping for 2 seconds...\n";
2018-10-07 16:50:45 +02:00
\sleep(2); // Blocking call in thread.
2017-05-18 09:51:31 +02:00
2016-08-18 18:04:48 +02:00
return 42;
});
2017-05-18 09:51:31 +02:00
2018-10-21 17:34:08 +02:00
\assert($context instanceof Thread);
2016-08-18 18:04:48 +02:00
print "Waiting 2 seconds to send start data...\n";
2017-05-26 11:55:08 +02:00
yield new Delayed(2000);
2017-05-18 09:51:31 +02:00
2016-08-18 18:04:48 +02:00
yield $context->send("Start data");
2017-05-18 09:51:31 +02:00
2018-10-07 16:50:45 +02:00
\printf("Received the following from child: %s\n", yield $context->receive());
\printf("Thread ended with value %d!\n", yield $context->join());
2016-08-18 18:04:48 +02:00
} finally {
Loop::cancel($timer);
2016-08-18 18:04:48 +02:00
}
});