mysql pessimistic locking and optimistic locking

The mysql lock mechanism is divided into table-level locks and row-level locks. This article will share with you my sharing and exchange of shared locks and exclusive locks in row-level locks in mysql.

Shared locks are also called read locks, or S locks for short. As the name suggests, shared locks are multiple transactions that can share a lock on the same data and can access the data, but they can only be read and cannot be modified.

Exclusive locks are also called write locks, or X locks for short. As the name implies, exclusive locks cannot coexist with others. For example, if a transaction acquires an exclusive lock on a data row, other transactions cannot acquire other locks on the row, including shared locks. And exclusive locks, but the transaction that acquires the exclusive lock can read and modify the data.

You may have a good understanding of shared locks, that is, multiple transactions can only read data and cannot change data. Your understanding of exclusive locks may be somewhat different. I made a mistake at first, thinking that after an exclusive lock locks a row of data, other The transaction cannot read and modify the row of data, which is not the case. An exclusive lock means that after a transaction adds an exclusive lock to a row of data, other transactions cannot add other locks to it. The default data modification statement of the mysql InnoDB engine, update, delete, and insert will automatically add exclusive locks to the data involved. The select statement will not add any lock type by default. If you add an exclusive lock, you can use the select ...for update statement. To add a shared lock, use the select ... lock in share mode statement. Therefore, the data row with exclusive lock cannot modify the data in other transactions, nor can the data be queried through the for update and lock in share mode locks, but the data can be queried directly through select ...from... because Normal queries do not have any locking mechanism.

Guess you like

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