PHP solves high concurrency problems
We know that when multiple threads write to the same file, there will be "thread safety" Question (Multiple threads run the same piece of code at the same time. If the result of each run is the same as that of a single-thread run, and the result is the same as expected, it is thread-safe). If it is a MySQL database, you can use its own lock mechanism to solve the problem. However, in large-scale concurrency scenarios, MySQL is not recommended.
In flash sales and rush sales scenarios, there is another problem, which is "over-sending". If this aspect is not controlled carefully, excessive sending will occur. We have also heard that some e-commerce companies conduct rush buying activities. After the buyer successfully purchases the product, the merchant does not recognize the order as valid and refuses to deliver the goods. The problem here may not necessarily be that the merchant is treacherous, but that it is caused by the risk of over-issuance at the technical level of the system.
1, Pessimistic lock ideas
There are many ideas to solve thread safety, and the discussion can start from the direction of "pessimistic lock".
Pessimistic lock, that is, when modifying data, the lock state is adopted to exclude modifications from external requests. When encountering a locked state, you must wait.
Although the above solution does solve the problem of thread safety, don't forget that our scenario is "high concurrency". In other words, there will be many such modification requests, and each request needs to wait for a "lock". Some threads may never have a chance to grab this "lock", and such requests will die there.
At the same time, there will be many such requests, which will instantly increase the average response time of the system. As a result, the number of available connections will be exhausted and the system will fall into an exception.
2. FIFO queue idea
Okay, then let’s slightly modify the above scenario. We directly put the request into the queue, using FIFO (First Input First Output, first in, first out), in this case, we will not cause some requests to never obtain the lock. Seeing this, does it feel like forcibly turning multi-threading into single-threading?
Then, we have now solved the lock problem, and all requests are processed in a "first in, first out" queue. Then a new problem comes. In a high-concurrency scenario, because there are many requests, the queue memory may be "exploded" in an instant, and then the system will fall into an abnormal state.
Or designing a huge memory queue is also a solution. However, the speed at which the system processes requests in a queue cannot be compared with the number of crazy influxes into the queue. In other words, more and more requests will accumulate in the queue. Eventually, the average response time of the Web system will still drop significantly, and the system will still fall into an exception.
3. The idea of file lock
For applications where the daily IP is not high or the number of concurrency is not very large, generally there is no need to consider these! There is no problem at all with normal file manipulation methods. But if the concurrency is high, when we read and write files, it is very likely that multiple processes will operate on the next file. If the access to the file is not exclusive at this time, it will easily cause data loss
Optimization plan 4: Use non-blocking file exclusive lock
<?php //优化方案4:使用非阻塞的文件排他锁 include ('./mysql.php'); //生成唯一订单号 function build_order_no(){ return date('ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8); } //记录日志 function insertLog($event,$type=0){ global $conn; $sql="insert into ih_log(event,type) values('$event','$type')"; mysqli_query($conn,$sql); } $fp = fopen("lock.txt", "w+"); if(!flock($fp,LOCK_EX | LOCK_NB)){ echo "系统繁忙,请稍后再试"; return; } //下单 $sql="select number from ih_store where goods_id='$goods_id' and sku_id='$sku_id'"; $rs = mysqli_query($conn,$sql); $row = $rs->fetch_assoc(); if($row['number']>0){//库存是否大于0 //模拟下单操作 $order_sn=build_order_no(); $sql="insert into ih_order(order_sn,user_id,goods_id,sku_id,price) values('$order_sn','$user_id','$goods_id','$sku_id','$price')"; $order_rs = mysqli_query($conn,$sql); //库存减少 $sql="update ih_store set number=number-{$number} where sku_id='$sku_id'"; $store_rs = mysqli_query($conn,$sql); if($store_rs){ echo '库存减少成功'; insertLog('库存减少成功'); flock($fp,LOCK_UN);//释放锁 }else{ echo '库存减少失败'; insertLog('库存减少失败'); } }else{ echo '库存不够'; insertLog('库存不够'); } fclose($fp); ?>
The above content is for reference only!
Recommended tutorial: PHP video tutorial
The above is the detailed content of How does php solve high concurrency?. For more information, please follow other related articles on the PHP Chinese website!

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software