If you have read the swoole task documentation carefully, you should have noticed this sentence
The number of task operations must be less than the onTask processing speed. If If the delivery capacity exceeds the processing capacity, the task will fill the cache area, causing the worker process to be blocked.
## worker process will not be able to receive new requests (Recommended Learning: SWOOLE Video Tutorials )
Task If it is blocked, it will cause the woker process to block, causing it The service is not working, causing problems.
I once used a task to send the link log of the service. A bug occurred in the service that received the log, which caused the task of sending the log to be blocked and then served gg. After that, I made a wave of optimizations to the task. .
The idea is to use swoole channel and swoole user process to implement a set of tasks.
Use the channel to receive data, and then consume the data in the user process. If the channel is full, it will only cause the push data to fail, and will not cause blocking. Because it is a link log, loss is allowed, so this solution is completely no problem.
The pseudocode of the channel consumption strategy in the swoole user process is as follows
$sleepTime = 5; $maxSleepTime = 100; while (true) { $task = $chan->pop(); if ($task === false) { $sleepTime = $sleepTime + 5; if ($sleepTime > $maxSleepTime) { $sleepTime = $maxSleepTime; } usleep($sleepTime * 1000); continue; } $sleepTime = 0; // 处理数据 }
If the channel data is consumed, an infinite loop is used to process the data, because during the data processing process There are other operations, so it doesn't take up a lot of CPU.
If the data cannot be consumed, sleep 5ms, and the sleep time is accumulated in sequence until it reaches the maximum value of 100ms, reaching a balance between CPU usage and real-time processing of data. The specific balance point can be determined according to your own business. Needs adjustment.
The above is the detailed content of Will the swoole task block?. For more information, please follow other related articles on the PHP Chinese website!