About the write lock function of mysql transaction row lock forupdate

Source: Internet
Author: User

In e-commerce, there is often a small inventory and a large number of buyers. In the case of high concurrency, how can we ensure that the number of products will not be bought multiple times.

In fact, it is very simple to use the transaction + for update to solve.

We all know that for update is actually a shared lock and can be read. But how can we not read it during execution.

To put it simply, assume that the inventory is 1 now and A and B are available for both purchase.

Start a transaction first

Begin;

Select stock from good where id = 1 for update; // query the number of stock items in the good table.

Check whether the stock is 0 in the program. (It's none of my business)

Finally, execute

Update good set stock = stock-1 where id = 1

Finally

Commit

However, at this time, B is also select 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 ensures the consistency of the remaining number of items as 1.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.