mirror of
https://github.com/danog/parallel.git
synced 2024-11-26 20:34:40 +01:00
Update examples
This commit is contained in:
parent
5eb0a6a241
commit
130732d4b5
@ -1,36 +0,0 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
|
||||
use Amp\Loop;
|
||||
use Amp\Parallel\Forking\Fork;
|
||||
|
||||
Loop::run(function () {
|
||||
$context = Fork::spawn(function () {
|
||||
print "Child sleeping for 4 seconds...\n";
|
||||
sleep(4);
|
||||
|
||||
yield $this->send('Data sent from child.');
|
||||
|
||||
print "Child sleeping for 2 seconds...\n";
|
||||
sleep(2);
|
||||
|
||||
return 42;
|
||||
});
|
||||
|
||||
$timer = Loop::repeat(1000, function () use ($context) {
|
||||
static $i;
|
||||
$i = $i ? ++$i : 1;
|
||||
print "Demonstrating how alive the parent is for the {$i}th time.\n";
|
||||
});
|
||||
|
||||
try {
|
||||
printf("Received the following from child: %s\n", yield $context->receive());
|
||||
printf("Child ended with value %d!\n", yield $context->join());
|
||||
} catch (Throwable $e) {
|
||||
print "Error from child!\n";
|
||||
print $e."\n";
|
||||
} finally {
|
||||
Loop::cancel($timer);
|
||||
}
|
||||
});
|
40
examples/parcel.php
Executable file
40
examples/parcel.php
Executable file
@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
|
||||
use Amp\Delayed;
|
||||
use Amp\Loop;
|
||||
use Amp\Parallel\Context\Thread;
|
||||
use Amp\Parallel\Sync\Parcel;
|
||||
use Amp\Parallel\Sync\ThreadedParcel;
|
||||
|
||||
Loop::run(function () {
|
||||
$parcel = new ThreadedParcel(1);
|
||||
|
||||
$context = Thread::spawn(function (Parcel $parcel) {
|
||||
$value = yield $parcel->synchronized(function (int $value) {
|
||||
return $value + 1;
|
||||
});
|
||||
|
||||
printf("Value after modifying in child thread: %s\n", $value);
|
||||
|
||||
yield new Delayed(2000); // Main thread should access parcel during this time.
|
||||
|
||||
// Unwrapping the parcel now should give value from main thread.
|
||||
printf("Value in child thread after being modified in main thread: %s\n", yield $parcel->unwrap());
|
||||
|
||||
yield $parcel->synchronized(function (int $value) {
|
||||
return $value + 1;
|
||||
});
|
||||
}, $parcel);
|
||||
|
||||
yield new Delayed(1000); // Give the thread time to start and access the parcel.
|
||||
|
||||
yield $parcel->synchronized(function (int $value) {
|
||||
return $value + 1;
|
||||
});
|
||||
|
||||
yield $context->join(); // Wait for child thread to finish.
|
||||
|
||||
printf("Final value of parcel: %d\n", yield $parcel->unwrap());
|
||||
});
|
@ -4,7 +4,7 @@ require dirname(__DIR__).'/vendor/autoload.php';
|
||||
|
||||
use Amp\Delayed;
|
||||
use Amp\Loop;
|
||||
use Amp\Parallel\Thread\Thread;
|
||||
use Amp\Parallel\Context\Thread;
|
||||
|
||||
Loop::run(function () {
|
||||
$timer = Loop::repeat(1000, function () {
|
||||
|
Loading…
Reference in New Issue
Block a user