Skip to content

Instantly share code, notes, and snippets.

@NHZEX
Created October 9, 2019 03:11
Show Gist options
  • Save NHZEX/86c2dc20747637055a35c729e61ce357 to your computer and use it in GitHub Desktop.
Save NHZEX/86c2dc20747637055a35c729e61ce357 to your computer and use it in GitHub Desktop.
pool test
<?php
# composer require nhzex/zsw-core
use Swoole\Runtime;
use unzxin\zswCore\Process\BaseSubProcess;
use unzxin\zswCore\ProcessPool;
use function HuangZx\ref_get_prop;
require_once __DIR__ . '/../vendor/autoload.php';
class Worker1 extends BaseSubProcess
{
protected $waitCoroutineStop = false;
protected function worker()
{
while (true) {
Co::sleep(1);
$mpool = $this->pool->getPool();
/**
* @var \Swoole\Process\Pool $swpool
*/
$swpool = ref_get_prop($mpool, 'swPool')->getValue();
$p = $swpool->getProcess($this->pool->getWorkerId(Worker2::class));
dump(self::class . '#wid ' . $this->pool->getWorkerId(self::class));
dump(self::class . '->' . Worker2::class . '#wid ' . $this->pool->getWorkerId(Worker2::class));
dump(self::class . '->' . Worker2::class . '#pin ' . $p->pid);
dump(self::class . '->' . Worker2::class . '#pipe ' . $p->pipe);
$socker = $p->exportSocket();
dump(self::class . '#send -> ' . Worker2::class);
$data = date('Y-m-d H:i:s') . '-' . mt_rand();
$data = serialize($data);
$this->sendIPCMessage($socker, $this->workerId, $data);
// $this->sendMessage($data, Worker2::class);
}
}
protected function onPipeMessage($data, ?string $form): bool
{
dump("$form -> $data");
return true;
}
protected function onExit(): void
{
}
}
class Worker2 extends BaseSubProcess
{
protected $waitCoroutineStop = false;
protected function worker()
{
$mpool = $this->pool->getPool();
/**
* @var \Swoole\Process\Pool $swpool
*/
$swpool = ref_get_prop($mpool, 'swPool')->getValue();
$process = $swpool->getProcess($this->pool->getWorkerId(self::class));
dump(self::class . '#start');
dump(self::class . '#wid ' . $this->pool->getWorkerId(self::class));
dump(self::class . '#pid ' . $process->pid);
dump(self::class . '#pipe ' . $process->pipe);
Co::sleep(3);
$this->process->exit();
}
protected function onPipeMessage($data, ?string $form): bool
{
dump(self::class . " recv: $form -> $data");
return true;
}
protected function onExit(): void
{
}
}
$pool = ProcessPool::makeSwooleProcess();
$pool->setLogger(new \Monolog\Logger('test'));
$w1 = new Worker1();
$pool->add($w1);
$w2 = new Worker2();
$pool->add($w2);
$pool->start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment