Home > PHP Framework > Swoole > body text

Does swoole support multi-threading?

青灯夜游
Release: 2019-12-25 18:18:24
Original
4140 people have browsed it

Does swoole support multi-threading?

Reactor thread

The main process of Swoole\Server is a multi-threaded program. There is a very important group of threads called Reactor threads. It is the thread that actually handles TCP connections and sends and receives data.

After accepting a new connection, Swoole's main thread will assign the connection to a fixed Reactor thread, and this thread will be responsible for monitoring the socket. Read the data when the socket is readable, perform protocol analysis, and deliver the request to the Worker process. Send data to the TCP client when the socket is writable.

The allocation calculation method is fd % serv->reactor_num

Since the PHP language does not support multi-threading, Swoole uses multi-process mode. There is process memory isolation in multi-process mode. When global variables and super-global variables are modified in the working process, it will be invalid in other processes.

When worker_num=1 is set, there is no process isolation and global variables can be used to save data

Process isolation

$fds = array();
$server->on('connect', function ($server, $fd){
    echo "connection open: {$fd}\n";
    global $fds;
    $fds[] = $fd;
    var_dump($fds);
});
Copy after login

Although $fds is a global variable, it is only valid within the current process. The bottom layer of the Swoole server will create multiple Worker processes. The value printed in var_dump($fds) only contains partial connected fds.

The corresponding solution is to use external storage services:

Database, such as: MySQL, MongoDB
Cache server, such as: Redis, Memcache
Disk files need to be locked when multiple processes read and write concurrently

Ordinary database and disk file operations have a lot of IO waiting time. Therefore, it is recommended to use:

Redis in-memory database, very fast read and write speed
/dev/shm in-memory file system, all read and write operations are completed in memory, no IO consumption, performance Extremely high
In addition to using storage, you can also use shared memory to save data

Recommended learning: swoole video tutorial

The above is the detailed content of Does swoole support multi-threading?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!