Home  >  Article  >  PHP Framework  >  How much do you know about swoole's processes and threads?

How much do you know about swoole's processes and threads?

coldplay.xixi
coldplay.xixiforward
2020-11-24 16:47:073598browse

swoole tutorial column introduces the process and thread of swoole.

How much do you know about swoole's processes and threads?

Recommended (free): swoole tutorial
Process

1. No status is shared between processes
2. Process scheduling is completed by the operating system
3. Each process has its own independent memory space
4. Inter-process communication is mainly achieved through signal transmission. There are many implementation methods. The communication efficiency of any method, such as semaphores, pipes, events, etc., needs to exceed the kernel, resulting in relatively low communication efficiency.
5. Since it is an independent memory space, the information of the first call stack needs to be saved when context switching. , information of each CPU register, virtual memory, and related opened handles, etc., so switching between context processes is very expensive and communication is troublesome.

Threads

1. Sharing variables between threads solves the problem of troublesome communication. Access to variables requires locks
2. A process can have multiple threads, but each of them Threads will share resources requested by the operating system from the parent process, including virtual memory, files, etc. Since they are shared resources, the system resources required to create threads are much smaller than those of processes, and the corresponding number of threads that can be created has also become relatively large. a lot of.
3. In addition, in terms of scheduling, because the memory is shared, there are fewer things that need to be saved when context switching, so that context switching becomes efficient.

Explanation
  • Running a php file through php is equivalent to us creating a process. This process will reside in the system and apply for its own memory. space system resources and run corresponding programs.
    How much do you know about swooles processes and threads?
swoole process

How much do you know about swooles processes and threads?
1. Master process: main process
2. Manger process: management process
3 , Worker process: Worker process
4. Task process: Asynchronous task worker process

  • The first layer, Master process, this is the main process of swoole, this process is used for processing The core event of swoole is driven, so in this process you can see that it has a MainReactor [thread] and several Reactor [threads]. All swoole's event monitoring will be implemented in these threads, such as connections from the client, signals Processing etc.

  • 1.1. MainReactor (main thread)
    The main thread will be responsible for monitoring the server socket. If there is a new connection accept, the main thread will evaluate the number of connections for each Reactor thread. Assign this connection to the reactor thread with the smallest number of connections to perform load balancing.

  • 1.2, Reactor thread group
    The Reactor thread is responsible for maintaining the TCP connection of the client machine, processing network IO, and sending and receiving data in a completely asynchronous and non-blocking mode.
    After accepting a new connection, the main thread of swoole will assign the connection to a fixed Reactor thread, 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.

  • 1.3. Heartbeat packet detection thread (HeartbeatCheck)
    After Swoole configures heartbeat detection, the heartbeat packet thread will send detection to all previously online connections within a fixed time
    Data packet

  • 1.4, UDP packet receiving thread (UdpRecv)
    Receive and process client udp data packet

  • swoole wants to achieve For best performance, multiple worker processes must be created to help process tasks, but the Worker process must be forked. However, the fork operation is unsafe. If there is no management, many zombie processes will appear, which will affect the server performance. At the same time, the worker process will be Inadvertent killing or abnormal exit due to program reasons, in order to ensure the stability of the service, the worker process needs to be re-created.

  • Swoole will create a separate management process during operation, and all worker processes and task processes are forked from the management process. The management process will monitor the exit events of all child processes. When a fatal error occurs in the worker process or the running life cycle ends, the management process will recycle the process and create a new process. In other words, the "nanny" Manager process has full authority to manage the creation and recycling of workers and task processes

  • The worker process belongs to the main logical process of swoole. The user processes a series of requests from the client, accepts the request packets delivered by the Reactor thread, and executes the PHP callback function to process the data to generate response data and sends it to the Reactor thread. , sent by the Reactor thread to the TCP client, can be in asynchronous non-blocking mode, or in synchronous blocking mode

  • The taskWorker process is an asynchronous worker process provided by swoole. These processes It is mainly used to handle some long-time synchronization tasks and deliver them in the worker process.

Interaction between client and server:

1. The client request reaches the Main Reactor. The Client actually connects to a Reactor thread in the Master process.

2. Main Reactor registers the request to the corresponding Reactor according to the Reactor situation (each Reactor has epoll. It is used to monitor changes in the client)

3. When there are changes in the client Reactor hands the data to the worker for processing

4. After the worker completes processing, it sends it to the corresponding reactor through inter-process communication (such as pipes, shared memory, message queues).

5. Reactor sends the response result to the corresponding connection request processing.

Callback function in the Master process
  • onStart Server starts in the main thread of the main process Callback this function
  • onShutdown This event occurs when the Server ends normally
Callback function within the Manager process
  • onManagerStart Call it when the management process starts
  • onManagerStop is called when the management process ends
  • onWorkerError When an exception occurs in the worker/task_worker process, this function will be called back in the Manager process
In the Worker process Callback function
  • onWorkerStart This event occurs when the Worker process/Task process starts
  • onWorkerStop This event occurs when the worker process terminates.
  • onConnect When a new connection comes in, it will be called back in the worker process
  • onClose After the TCP client connection is closed, this function will be called back in the worker process
  • onReceive data received This function is called back when a UDP packet is received.
  • onPacket This function is called back when a UDP packet is received.
  • onFinish When the task delivered by the worker process is completed in task_worker , the task process will send the task processing results to the worker process through the finish() method.
  • onWorkerExit is only valid after enabling the reload_async feature. Asynchronous restart feature
  • onPipeMessage When the worker process receives the pipe message sent by sendMessage, the event will be triggered
Callback function in the Task process
  • onTask Called within the task_worker process. The worker process can use the swoole_server_task function to deliver new tasks to the task_worker process
  • onWorkerStart This event occurs when the Worker process/Task process starts
  • onPipeMessage When the worker process receives the pipe message sent by sendMessage Events will be triggered
Simple description:
  • 1. The last event when the server shutdown program terminates is onShutdown.
  • 2. After the server is started successfully, onStart/onManagerStart/onWorkerStart will be executed concurrently in different processes, not sequentially.
  • 3. All event callbacks occur after $server->start. Code written after start is invalid code.
  • 4. The execution order of the three events onStart/onManagerStart/onWorkerStart is uncertain
swoole operation flow chart

How much do you know about swooles processes and threads?

set([
    'worker_num'=>3, //设置进程
    //'heartbeat_idle_time'=>10,//连接最大的空闲时间
    //'heartbeat_check_interval'=>3 //服务器定时检查
    'open_length_check'=>1,
    'package_length_type'=>'N',//设置包头的长度
    'package_length_offset'=>0, //包长度从哪里开始计算
    'package_body_offset'=>4,  //包体从第几个字节开始计算
    'package_max_length'=>1024 * 1024 * 2,]);$server->on("Start",function (){

    var_dump(1);
     //设置主进程的名称
     swoole_set_process_name("server-process:master");});//服务关闭时候触发(信号)$server->on("shutdown",function (){});//当管理进程启动时调用它$server->on('ManagerStart',function (){
    var_dump(2);
    //swoole_set_process_name("server-process:manger");});$server->on('WorkerStart',function ($server,$workerId){
   // swoole_set_process_name("server-process:worker");
    var_dump(3);});//监听事件,连接事件(woker进程当中)$server->on('connect',function ($server,$fd){
    echo "新的连接进入:{$fd}".PHP_EOL;});//消息发送过来(woker进程当中)$server->on('receive',function (swoole_server $server, int $fd, int $reactor_id, string $data){
    //var_dump("消息发送过来:".$data);
    //服务端});//消息关闭$server->on('close',function (){
    echo "消息关闭".PHP_EOL;});//服务器开启$server->start();echo '123456';
Process

1. No state is shared between processes
2. Process scheduling is completed by the operating system
3. Each process has its own independent memory space
4. Inter-process communication is mainly achieved through signal transmission. There are many implementation methods, such as semaphores, pipes, events, etc., any method The communication efficiency needs to go through the kernel, resulting in relatively low communication efficiency
5. Since it is an independent memory space, when context switching, it is necessary to save the information of the first call stack, the information of each CPU register, virtual memory, and open related Handle and other information, so switching between context processes is very expensive and communication is troublesome.

Threads

1. Sharing variables between threads solves the problem of troublesome communication. Access to variables requires locks
2. A process can have multiple threads, but each thread will share The parent process applies for resources from the operating system, including virtual memory, files, etc. Since it is a shared resource, the system resources required to create a thread are much smaller than that of the process, and the corresponding number of threads that can be created becomes relatively larger.
3. In addition, in terms of scheduling, because the memory is shared, there are fewer things that need to be saved when context switching, so that context switching becomes efficient.

Explanation
  • Running a php file through php is equivalent to us creating a process. This process will reside in the system and apply for its own memory. space system resources and run corresponding programs.
    How much do you know about swooles processes and threads?
swoole process

How much do you know about swooles processes and threads?
1. Master process: main process
2. Manger process: management process
3 , Worker process: Worker process
4. Task process: Asynchronous task worker process

  • The first layer, Master process, this is the main process of swoole, this process is used for processing The core event of swoole is driven, so in this process you can see that it has a MainReactor [thread] and several Reactor [threads]. All swoole's event monitoring will be implemented in these threads, such as connections from the client, signals Processing etc.

  • 1.1. MainReactor (main thread)
    The main thread will be responsible for monitoring the server socket. If there is a new connection accept, the main thread will evaluate the number of connections for each Reactor thread. Assign this connection to the reactor thread with the smallest number of connections to perform load balancing.

  • 1.2, Reactor thread group
    The Reactor thread is responsible for maintaining the TCP connection of the client machine, processing network IO, and sending and receiving data in a completely asynchronous and non-blocking mode.
    After accepting a new connection, the main thread of swoole will assign the connection to a fixed Reactor thread, 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.

  • 1.3. Heartbeat packet detection thread (HeartbeatCheck)
    After Swoole configures heartbeat detection, the heartbeat packet thread will send detection to all previously online connections within a fixed time
    Data packet

  • 1.4, UDP packet receiving thread (UdpRecv)
    Receive and process client udp data packet

  • swoole wants to achieve For best performance, multiple worker processes must be created to help process tasks, but the Worker process must be forked. However, the fork operation is unsafe. If there is no management, many zombie processes will appear, which will affect the server performance. At the same time, the worker process will be Inadvertent killing or abnormal exit due to program reasons, in order to ensure the stability of the service, the worker process needs to be re-created.

  • Swoole will create a separate management process during operation, and all worker processes and task processes are forked from the management process. The management process will monitor the exit events of all child processes. When a fatal error occurs in the worker process or the running life cycle ends, the management process will recycle the process and create a new process. In other words, the "nanny" Manager process has full authority to manage the creation and recycling of workers and task processes.

  • The worker process belongs to the main logical process of swoole and is handled by the user. A series of requests from the client accept the request packets delivered by the Reactor thread, and execute the PHP callback function to process the data to generate response data and send it to the Reactor thread. The response data sent by the Reactor thread to the TCP client can be in asynchronous non-blocking mode or synchronously. Blocking mode

  • The taskWorker process is an asynchronous worker process provided by swoole. These processes are mainly used to process some long-time synchronous tasks and deliver them in the worker process.

Interaction between client and server:

1. The client request reaches the Main Reactor. The Client actually connects to a Reactor thread in the Master process.

2. Main Reactor registers the request to the corresponding Reactor according to the Reactor situation (each Reactor has epoll. It is used to monitor changes in the client)

3. When there are changes in the client Reactor hands the data to the worker for processing

4. After the worker completes processing, it sends it to the corresponding reactor through inter-process communication (such as pipes, shared memory, message queues).

5. Reactor sends the response result to the corresponding connection request and the processing is completed

Callback function in the Master process
  • onStart Server starts to call back this function on the main thread of the main process
  • onShutdown This event occurs when the Server ends normally
Callback function within the Manager process
  • onManagerStart is called when the management process starts
  • onManagerStop is called when the management process ends
  • onWorkerError when the worker After an exception occurs in the /task_worker process, this function will be called back in the Manager process
Callback function in the Worker process
  • onWorkerStart This event occurs when the Worker process/Task process starts
  • onWorkerStop This event occurs when the worker process terminates.
  • onConnect When a new connection comes in, it will be called back in the worker process
  • onClose After the TCP client connection is closed, this function will be called back in the worker process
  • onReceive data received This function is called back when a UDP packet is received.
  • onPacket This function is called back when a UDP packet is received.
  • onFinish When the task delivered by the worker process is completed in task_worker , the task process will send the task processing results to the worker process through the finish() method.
  • onWorkerExit is only valid after enabling the reload_async feature. Asynchronous restart feature
  • onPipeMessage When the worker process receives the pipe message sent by sendMessage, the event will be triggered
Callback function in the Task process
  • onTask Called within the task_worker process. The worker process can use the swoole_server_task function to deliver new tasks to the task_worker process
  • onWorkerStart This event occurs when the Worker process/Task process starts
  • onPipeMessage When the worker process receives the pipe message sent by sendMessage Events will be triggered
Simple description:
  • 1. The last event when the server shutdown program terminates is onShutdown.
  • 2. After the server is started successfully, onStart/onManagerStart/onWorkerStart will be executed concurrently in different processes, not sequentially.
  • 3. All event callbacks occur after $server->start. Code written after start is invalid code.
  • 4. The execution order of the three onStart/onManagerStart/onWorkerStart events is uncertain
swoole operation flow chart

How much do you know about swooles processes and threads?

set([
    'worker_num'=>3, //设置进程
    //'heartbeat_idle_time'=>10,//连接最大的空闲时间
    //'heartbeat_check_interval'=>3 //服务器定时检查
    'open_length_check'=>1,
    'package_length_type'=>'N',//设置包头的长度
    'package_length_offset'=>0, //包长度从哪里开始计算
    'package_body_offset'=>4,  //包体从第几个字节开始计算
    'package_max_length'=>1024 * 1024 * 2,]);$server->on("Start",function (){

    var_dump(1);
     //设置主进程的名称
     swoole_set_process_name("server-process:master");});//服务关闭时候触发(信号)$server->on("shutdown",function (){});//当管理进程启动时调用它$server->on('ManagerStart',function (){
    var_dump(2);
    //swoole_set_process_name("server-process:manger");});$server->on('WorkerStart',function ($server,$workerId){
   // swoole_set_process_name("server-process:worker");
    var_dump(3);});//监听事件,连接事件(woker进程当中)$server->on('connect',function ($server,$fd){
    echo "新的连接进入:{$fd}".PHP_EOL;});//消息发送过来(woker进程当中)$server->on('receive',function (swoole_server $server, int $fd, int $reactor_id, string $data){
    //var_dump("消息发送过来:".$data);
    //服务端});//消息关闭$server->on('close',function (){
    echo "消息关闭".PHP_EOL;});//服务器开启$server->start();echo '123456';

The above is the detailed content of How much do you know about swoole's processes and threads?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete