MySQL transaction row lock for update realizes the function of write lock

       In e-commerce, there is often a small amount of inventory and many people who buy it. How to ensure that the number of goods will not be purchased multiple times in the case of large concurrency. In fact, it is very simple, and it can be solved by using transaction + for update. We all know that for update is actually a shared lock that can be read. But how can it not be read during execution.

       To put it simply: Suppose the current inventory is 1, and now there are A and B buying at the same time

1. Start a transaction and execute sql

select stock from good where id=1 for update;//Query the quantity of stock in a commodity in the good table

2. After finding out, in the program it is judged whether the stock is 0 (what language do you use, none of my business)

3. Next execute

update good set stock=stock-1 where id=1;

4. Finally

commit;

But at this time, B also selects stock from good where id=1 for update; Note: for update cannot be omitted. . At this time, it will be locked and cannot be read. Therefore, this can ensure the consistency of the remaining quantity of goods being 1.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326511105&siteId=291194637