Home  >  Article  >  Backend Development  >  Several methods of concurrency processing in php

Several methods of concurrency processing in php

王林
王林Original
2019-10-10 17:50:503323browse

Several methods of concurrency processing in php

In concurrent scenarios such as product rush buying, overselling may occur. At this time, it is necessary to solve these problems caused by concurrency.

There is no native concurrency solution in the PHP language, so other methods are needed to achieve concurrency control.

Option 1: Use file lock exclusive lock

Theflock function is used to acquire the file lock. This lock can only be acquired by one thread at the same time, and no other threads are acquired. The thread that gets the lock is either blocked or fails to acquire it. When acquiring the lock, first query the inventory. If the inventory is greater than 0, place an order, reduce the inventory, and then release the lock.

Option 2: Use the pessimistic lock provided by the MySQL database

Innodb storage engine supports row-level locks. When a row of data is locked, other processes cannot lock the row. Data is operated on.

Query and lock the row first:

select stock_num from table where id=1 for update
if(stock_num > 0){
//下订单
update table set stock_num=stock-1 where id=1
}

Option 3: Use the queue

to store the user’s order request in a queue in sequence, in the background Use a separate process to handle order requests in the queue.

Option 4: Use Redis

The operations of redis are all atomic. You can store the inventory of goods in redis and perform decr operation on the inventory before placing an order. , if the returned value is greater than or equal to 0, you can place an order, otherwise you cannot place an order. This method is more efficient.

if(redis->get('stock_num') > 0){
 stock_num = redis->decr('stock_num')
 if(stock_num >= 0){
 //下订单
 }else{
 //库存不足
 }
}else{
//库存不足
}

Recommended tutorial: PHP video tutorial

The above is the detailed content of Several methods of concurrency processing in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:php gets WeChat openidNext article:php gets WeChat openid

Related articles

See more