Process\Pool is a Process Pool provided by Swoole, which is implemented by Server Manager management Process module and can manage multiple worker processes.
The core function of this module is Process management. Compared with Process to achieve multiple processes, Process\Pool is simpler and has a higher encapsulation level. Developers can achieve Process management functions without writing too much code. A server program that can take advantage of multi-core cpus.
In version 4.7, a detach method was added to Process\Pool. Does this method name look familiar?
There is also a detach method in Http\Response that detaches the Response object. With this method, the $response object is destroyed without an automatic end, and is used in conjunction with Http\Response::create and Server->send.
Methods effect
The role of Process\Pool::detach() is obvious:
If the current Worker process in the process pool is removed from management, the bottom layer will immediately create a new process, and the old process will no longer process data, and the application layer code will manage the life cycle by itself.
The sample code
Take a look at the sample code below:
use Swoole\Process;
use Swoole\Coroutine;
$pool = new Process\Pool(2);
$pool->set(['enable_coroutine'= >true]);
$pool->on('WorkerStart'.function (Process\Pool $pool.$workerId) {
static $running = true;
Process::signal(SIGTERM, function () use (&$running) {
$running = false;
echo "TERM\n";
});
echo("[Worker #{$workerId}] WorkerStart, pid: " . posix_getpid() . "\n");
$i = 0;
while ($running) {
Coroutine::sleep(1);
$i+ +;if ($i= =5) {
$pool->detach();
} elseif ($i= =10) {
break; }}});$pool->on('WorkerStop'.function (Process\Pool $pool.$workerId) {
echo("[Worker #{$workerId}] WorkerStop, pid: " . posix_getpid() . "\n");
});
$pool->start();
Copy the code
Set up an asynchronous signal listener in WorkerStart with Process:: Signal, which can be stopped by sending a SIGTERM signal.
When $I = 5, remove the current process from management. At the same time, new processes are created at the bottom to maintain worker_num numbers; When $I equals 10, the process is terminated.
So you get the following output:
[Worker #0] WorkerStart, pid: 75050
[Worker #1] WorkerStart, pid: 75051
[Worker #0] WorkerStart, pid: 75054
[Worker #1] WorkerStart, pid: 75055
[Worker #0] WorkerStop, pid: 75050
[Worker #1] WorkerStop, pid: 75051
[Worker #1] WorkerStart, pid: 75056
[Worker #0] WorkerStart, pid: 75057
Copy the code
This is equivalent to maintaining four processes in the code above, and then pulling up two new processes after one exit, and so on.
You need to pay special attention to logic issues when you use it, otherwise you may end up creating new processes indefinitely.
The article starts from Swoole’s official Q&A “Process\Pool:: Detach ()”, a preview of Swoole V4.7’s new features. Welcome to follow Swoole’s official account and Get new information as soon as possible.