Created
May 17, 2022 17:41
-
-
Save lotharthesavior/84a7a788f6fb89570e90f1f9c82aac6c to your computer and use it in GitHub Desktop.
OpenSwoole Yield/Resume Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env php | |
<?php | |
declare(strict_types=1); | |
class DataObject | |
{ | |
public $total = 0; | |
public $data = []; | |
public function push($item) | |
{ | |
$this->data[] = $item; | |
} | |
public function sum() | |
{ | |
$this->total = array_sum($this->data); | |
} | |
} | |
$data = new DataObject; | |
Co\run(function() use (&$data) { | |
$co1 = go(function () use (&$data) { | |
$data->push(1); | |
Co::yield(); | |
$data->push(3); | |
Co::yield(); | |
$data->push(5); | |
}); | |
$co2 = go(function () use (&$data) { | |
$data->push(2); | |
Co::yield(); | |
$data->push(4); | |
Co::yield(); | |
$data->push(6); | |
}); | |
// process | |
Co::resume($co1); | |
Co::resume($co2); | |
Co::resume($co1); | |
Co::resume($co2); | |
}); | |
echo implode(',', $data->data) . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment