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

42 lines
1.2 KiB
PHP
Raw Normal View History

2017-11-30 03:17:49 +01:00
#!/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\Channel;
2017-11-30 03:17:49 +01:00
use Amp\Parallel\Sync\Parcel;
use Amp\Parallel\Sync\ThreadedParcel;
Loop::run(function () {
$parcel = new ThreadedParcel(1);
2017-12-11 00:01:10 +01:00
$context = Thread::run(function (Channel $channel, Parcel $parcel) {
2017-11-30 03:17:49 +01:00
$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());
});