2017-11-30 03:17:49 +01:00
|
|
|
#!/usr/bin/env php
|
|
|
|
<?php
|
2018-10-07 16:50:45 +02:00
|
|
|
require \dirname(__DIR__).'/vendor/autoload.php';
|
2017-11-30 03:17:49 +01:00
|
|
|
|
|
|
|
use Amp\Delayed;
|
|
|
|
use Amp\Loop;
|
|
|
|
use Amp\Parallel\Context\Thread;
|
2017-12-10 23:43:19 +01:00
|
|
|
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);
|
|
|
|
|
2018-10-21 17:34:08 +02:00
|
|
|
$context = yield 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;
|
|
|
|
});
|
|
|
|
|
2018-10-07 16:50:45 +02:00
|
|
|
\printf("Value after modifying in child thread: %s\n", $value);
|
2017-11-30 03:17:49 +01:00
|
|
|
|
2017-12-13 06:38:23 +01:00
|
|
|
yield new Delayed(500); // Main thread should access parcel during this time.
|
2017-11-30 03:17:49 +01:00
|
|
|
|
|
|
|
// Unwrapping the parcel now should give value from main thread.
|
2018-10-07 16:50:45 +02:00
|
|
|
\printf("Value in child thread after being modified in main thread: %s\n", yield $parcel->unwrap());
|
2017-11-30 03:17:49 +01:00
|
|
|
|
|
|
|
yield $parcel->synchronized(function (int $value) {
|
|
|
|
return $value + 1;
|
|
|
|
});
|
|
|
|
}, $parcel);
|
|
|
|
|
2018-10-21 17:34:08 +02:00
|
|
|
\assert($context instanceof Thread);
|
|
|
|
|
2017-12-13 06:38:23 +01:00
|
|
|
yield new Delayed(100); // Give the thread time to start and access the parcel.
|
2017-11-30 03:17:49 +01:00
|
|
|
|
|
|
|
yield $parcel->synchronized(function (int $value) {
|
|
|
|
return $value + 1;
|
|
|
|
});
|
|
|
|
|
|
|
|
yield $context->join(); // Wait for child thread to finish.
|
|
|
|
|
2018-10-07 16:50:45 +02:00
|
|
|
\printf("Final value of parcel: %d\n", yield $parcel->unwrap());
|
2017-11-30 03:17:49 +01:00
|
|
|
});
|