2
头图

060accaaeb11cb is a process pool provided by Process\Pool Server , which can manage multiple work processes.

The core function of this module is process management. Compared with Process achieve multi-process, Process\Pool is simpler and has a higher encapsulation level. Developers can achieve process management functions without writing too much code. With Coroutine\Server a pure coroutine style can be created. Server program using multi-core CPU.

In the 4.7 version, for Process\Pool added a detach method that names look familiar, right?

Http\Response is also a detach method in 060accaaeb127b, its role is to separate the response object. After using this method, $response will not be automatically destroyed when the end in conjunction with Http\Response::create and Server->send .

Method effect

Then the role of Process\Pool::detach()

If the current Worker process in the process pool is separated from management, the bottom layer will immediately create a new process, the old process no longer processes data, and the application layer code manages the life cycle by itself.

Sample code

Let's take a look at the sample code:

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();

In WorkerStart , set an asynchronous signal monitoring Process::signal , and you can stop the service SIGTERM

When the service is running, when $i is equal to 5, let the current process out of management; at the same time, a new process will be created at the bottom layer to maintain the number of worker_num $i is equal to 10, the process is terminated.

So you will 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

In the above code, it is equivalent to maintaining 4 processes, and two new processes will be pulled up again after exiting once, and so on.

You need to pay special attention to logic issues when using it, otherwise it may cause unlimited creation of new processes.


沈唁
1.9k 声望1.2k 粉丝