Understand the principle of Mysql lock mechanism

1. What is a lock?

In a database, a lock is a mechanism used to control concurrent access by multiple transactions to the same resource in the database. By setting locks on data rows or tables, we can avoid data inconsistency and ensure the atomicity, consistency, isolation, and durability of transactions. These four characteristics are referred to as ACID characteristics.

There are two main types of locks: shared locks (Shared Lock) and exclusive locks (Exclusive Lock). A shared lock allows multiple transactions to read the same resource, but prevents any transaction from writing; an exclusive lock allows only one transaction to read and write to the resource, preventing any access by other transactions.

2. MySQL lock mechanism

MySQL implements various types of locks, including table locks, row locks, and more advanced intent locks.

Table Locks: MySQL automatically locks tables when performing operations such as SELECT, INSERT, UPDATE, and DELETE. Among them, read operations (such as SELECT) will add shared locks, and write operations (such as UPDATE, INSERT, DELETE) will add exclusive locks. The advantages of table locks are simple implementation, low overhead, and no deadlocks. The disadvantage is that the concurrency performance is poor, and it is only suitable for scenarios with more reads and fewer writes.
Row Locks: Row locks are a finer-grained lock implemented by the InnoDB storage engine in MySQL, which can lock a single row of data. Row locks are automatically locked when executing SELECT, UPDATE, and DELETE. The advantage of row lock is that it has good concurrency performance and is suitable for high concurrency OLTP systems. The disadvantage is that the implementation is complicated and deadlock may occur.
Intention Locks: Intention Locks are a special lock in the InnoDB storage engine, used to optimize switching between table locks and row locks. Intention locks are divided into intention shared locks and intention exclusive locks, which correspond to shared locks and exclusive locks of row locks respectively.

3. MySQL transaction isolation level and lock

A transaction is a logical processing unit composed of a set of SQL statements. A transaction has ACID characteristics, namely Atomicity, Consistency, Isolation, and Durability. In MySQL, the isolation level of a transaction determines the changes that a transaction may see made by other concurrent transactions.

MySQL supports the following four transaction isolation levels:

READ UNCOMMITTED (READ UNCOMMITTED): At this level, transactions can read the changes of other uncommitted transactions. This level can lead to dirty reads, non-repeatable reads, and phantom reads. At this level, MySQL only locks for write operations.
READ COMMITTED: At this level, a transaction can only read the changes of other committed transactions. This level can avoid dirty reads, but non-repeatable reads and phantom reads may occur. At this level, MySQL locks both reads and writes.
Repeatable read (REPEATABLE READ): At this level, a transaction can read the same row of data multiple times throughout the process, and the results are always consistent. This level can avoid dirty reads and non-repeatable reads, but phantom reads may occur. At this level, MySQL locks both reads and writes, using a mechanism called Multiversion Concurrency Control (MVCC).
Serialization (SERIALIZABLE): At this level, transactions are executed completely serially, which can avoid dirty reads, non-repeatable reads, and phantom reads, but the concurrency performance is poor. At this level, MySQL locks both reads and writes, and all reads block other transactions.
The isolation level of a transaction can be set with the following statement:

SET TRANSACTION ISOLATION LEVEL [级别名];

4. Deadlock and how to deal with it

In a database system, a deadlock occurs when two or more transactions are waiting for each other to release resources. MySQL provides several tools to detect and resolve deadlocks. For example, the InnoDB storage engine will automatically perform deadlock detection when a deadlock occurs, and actively roll back one of the transactions to resolve the deadlock.

Although InnoDB can automatically handle deadlocks, in order to improve system performance, we should still try to avoid deadlocks. Here are some common strategies for avoiding deadlocks:

Minimize the time that transactions hold locks to reduce the possibility of deadlocks.
Try to access database objects in the same order to avoid circular waits.
Use a lower transaction isolation level such as READ COMMITTED.
With lock timeouts, transactions are automatically rolled back if they try to acquire a lock for longer than a certain amount of time.

5. Optimize the locking mechanism of MySQL

Although the MySQL database has a powerful concurrency control mechanism, how to use and optimize the lock mechanism reasonably is still an important means to improve database performance in high concurrency scenarios. Here we provide several strategies for optimizing the MySQL locking mechanism:

Lock upgrade and downgrade: When concurrent transactions access the same resource, lock upgrade and downgrade can be performed as needed. For example, when a data table needs to be read multiple times, the shared lock can be upgraded to an exclusive lock to avoid the overhead of repeatedly acquiring and releasing the lock; when the write operation is completed, the exclusive lock can be downgraded to a shared lock, allowing Other transactions perform read operations.
Choose the appropriate isolation level: The choice of isolation level needs to find a balance between concurrency performance and data consistency. In some scenarios that read more and write less, you can choose a lower isolation level, such as READ COMMITTED, to improve concurrency performance; in scenarios that need to ensure strong data consistency, you need to choose a higher isolation level, such as SERIALIZABLE.
Use row locks as much as possible: In the InnoDB storage engine, using row locks as much as possible can greatly improve concurrency performance. This is because the granularity of row locks is small, and multiple transactions can lock different rows at the same time without conflicts. It should be noted that the use of row locks requires the correct creation and use of indexes, otherwise InnoDB may degenerate into the use of table locks.
Reduce the time to lock resources: Another strategy to improve concurrency performance is to reduce the time to lock resources. This can be achieved by reducing the size of the transaction and splitting a large transaction into multiple small transactions; it can also be achieved by improving the execution efficiency of the SQL statement and reducing the execution time of the transaction.

6. Lock combat

Next, let's use a practical problem scenario to see how to use MySQL's locking mechanism to analyze and solve problems.

Scenario: In an e-commerce application, when a user submits an order, the system needs to subtract the quantity of purchased items from the inventory. This operation needs to guarantee atomicity, that is, it is impossible for a commodity to be oversold.

Analysis: In this scenario, we can use an exclusive lock to lock the inventory record of the product to ensure that other transactions cannot modify the inventory during the execution of the inventory reduction operation.

Solution: The following is the SQL statement to achieve this operation:


```sql
START TRANSACTION;
SELECT * FROM inventory WHERE product_id = 1 FOR UPDATE;
UPDATE inventory SET quantity = quantity - 1 WHERE product_id = 1;
COMMIT;

在这个例子中,我们使用FOR UPDATE语句获取了一个排他锁,然后执行了更新操作,最后提交了事务,释放了锁。这样就确保了在减库存的操作执行期间,其他事务无法修改库存,避免了超卖的情况。

最后,需要强调的是,虽然锁机制对于保证数据的一致性和并发控制至关重要,但合理使用和优化锁机制需要根据具体的应用场景和需求进行。只有深入理解了锁机制的工作原理,才能根据需要选择合适的锁类型和隔离级别,有效地避免死锁,提高数据库的并发性能。

Guess you like

Origin blog.csdn.net/Hx230/article/details/132227654