database lock

Lock is a concurrency control technology that protects data when multiple users access the same data at the same time.
1. Lock type
shared (S) lock : Multiple transactions can block a shared page ; no transaction can modify the page; usually, the S lock is released immediately after the page is read. When executing the select statement, you need to add a shared lock to the operation object (table or some records), but you need to check whether there is an exclusive lock before locking . If not, you can add a shared lock ( n shared locks can be added to an object). ), otherwise not. Shared locks are usually released after the select statement is executed. Of course, it may be released at the end of the transaction (including normal end and abnormal end), which mainly depends on the transaction isolation level set by the database.
Exclusive (X) lock : Only one transaction is allowed to block this page ; any other transaction must wait until the X lock is released to access the page; the X lock cannot be released until the end of the transaction. When executing insert, update, and delete statements, you need to add an exclusive lock to the object of the operation. Before adding an exclusive lock, you must confirm that there are no other locks on the object. Once an exclusive lock is added, you cannot add any other locks to this object. . The release of the exclusive lock is usually at the end of the transaction (of course there are exceptions, that is, when the database transaction isolation level is set to Read Uncommitted (read uncommitted data), in this case, the exclusive lock will be released after the update operation is performed. release, not at the end of the transaction)

2.
Four necessary conditions for deadlock to occur :
(1) Mutual exclusion condition: A resource can only be used by one process at a time.
(2) Request and hold conditions: When a process is blocked due to requesting resources, it will hold on to the obtained resources.
(3) Inalienable condition: The resources that the process has obtained cannot be forcibly deprived before the end of the use.

2.1 Prevention of deadlock To
prevent the occurrence of deadlock, it is only necessary to destroy one of the four necessary conditions for the occurrence of deadlock.
1) Destruction of mutual exclusion conditions If all system resources are allowed to be shared, the system will not enter a deadlock state. However, some resources cannot be accessed at the same time at all, and critical resources such as printers can only be used mutually exclusively. Therefore, it is not feasible to break the mutual exclusion condition to prevent deadlock , and in some cases this mutual exclusion should be protected.
2) Destruction of the non-preemption condition When a process that has maintained some inalienable resources requests new resources and cannot be satisfied, it must release all the resources it has maintained and reapply when it is needed later. This means that a resource occupied by a process will be temporarily released, or deprived, or the inalienability condition will be violated. This strategy is complicated to implement. Releasing the acquired resources may cause the failure of the previous stage of work. Repeatedly applying and releasing resources will increase the system overhead and reduce the system throughput . This method is often used for resources whose state is easy to save and restore, such as CPU registers and memory resources, but generally cannot be used for resources such as printers.
3) The pre- , that is, the process applies for all the resources it needs at one time before running , and does not put it into operation until its resources are not met. Once put into operation, these resources are always owned by it, and no other resource requests are made, so that the system can not be deadlocked.
4) Destruction of the cyclic waiting condition In order to destroy the cyclic waiting condition, the sequential resource allocation method can be used . First, number the resources in the system, and stipulate that each process must request resources in the order of increasing numbers, and the same resources should be applied for at one time. That is to say, as long as a process applies for allocating resources Ri, the process can only apply for resources whose numbers are greater than Ri in subsequent resource applications. The problem with this approach is that the numbering has to be relatively stable, which limits the addition of new types of devices;Although the order in which most jobs actually use these resources has been taken into account when numbering resources, it often happens that the order in which the job dumps resources is different from the order specified by the system, resulting in a waste of resources; The method of applying for resources in sequence will inevitably bring trouble to the user's programming.

2.2. Avoid Deadlock
Banker's Algorithm.

2.3. Detect deadlock
Deadlock management.

2.4. Removing deadlocks
2.4.1 Depriving resources from deadlocked processes
2.4.2 Terminating some or all processes

3. Two mechanisms of database locks
3.1 Pessimistic lock
1. Exclusive lock, when a transaction is operating data, this part of the data is locked until the operation is completed and then unlocked, other transaction operations can operate this part of the data. This will prevent other processes from reading or modifying the data in the table.
2. Implementation: In most cases, it is implemented by the locking mechanism of the database

3.2 Optimistic locking
1. If someone updates before you, your update should be rejected and the user can re-operate .
2. Implementation: Most implementations are based on the data version (Version) recording mechanism .
Specifically by adding a version number or timestamp field to the table. When reading data, the value of the version field is read together. Every time the data is updated, Add one to this version value . When we submit the update, we judge the size of the current version information and the version value taken out for the first time. If the current version number of the database table is equal to the version value taken out for the first time, it will be updated. Otherwise, it will be considered as expired data and rejected. Update, let the user do it again.
If the amount of concurrency is high, it is recommended to use pessimistic locking, otherwise optimistic locking is used

4. The granularity of mysql locks
MySQL storage engines use three types (levels) of locking mechanisms: row-level locking, page-level locking and table-level locking.
4.1. Table-level lock : directly lock the entire table. During your lock period, other processes cannot write to the table. If you are a write lock, other processes are not allowed to read . Features: low overhead and fast locking; no deadlock; the largest locking granularity, the highest probability of lock conflict, and the lowest concurrency.

There are 2 modes: table shared read lock and table exclusive write lock . The command to add a read lock: lock table table name read; the command to remove the lock: unlock tables.

Lock scheduling mechanism : write locks take precedence. A process requests a read lock on a MyISAM table, and another process also requests a write lock on the same table. How does MySQL handle it? The answer is that the writer process acquires the lock first

4.2. Row-level locks only lock the specified records, so that other processes can still operate on other records in the same table. Features: High overhead, slow locking; deadlocks; the smallest locking granularity, the lowest probability of lock conflicts, and the highest concurrency .
The InnoDB storage engine supports both row-level locks and table-level locks, but row-level locks are used by default.

4.3. Page-level lock, which locks a group of adjacent records at a time. Overhead and locking time are bounded between table locks and row locks; deadlocks will occur; locking granularity is bounded between table locks and row locks, and the degree of concurrency is average. The most common way to handle concurrent access by multiple users is locking. When a user locks an object in the database, other users can no longer access the object. The impact of locking on concurrent access is reflected in the granularity of the lock. For example, (table locks) locks placed on a table restrict concurrent access to the entire table; (page locks) locks placed on data pages restrict access to entire data pages; (row locks) locks placed on rows The lock only restricts concurrent access to the row

MySQL intent lock
① There is a table lock in MySQL,
LOCK TABLE my_tabl_name READ; using a read lock to lock the table will block other transactions from modifying the table data.
LOCK TABLE my_table_name WRITE; Locking the table with a write lock will block other transactions from reading and writing.
②Innodb engine also supports row locks, row locks are divided into
shared locks (read locks), a shared read-only lock for a row by a transaction.
Exclusive lock , an exclusive read-write lock on a row by a transaction.
③ The problem of the coexistence of these two types of locks
Consider this example:
Transaction A locks a row in the table, so that this row can only be read but not written.
After that, transaction B applies for a write lock on the entire table.
If transaction B applies successfully, then theoretically it can modify any row in the table, which conflicts with the row lock held by A.
The database needs to avoid this conflict, which means that B's application is blocked until A releases the row lock.
How does the database determine this conflict?
Step1: Determine whether the table has been locked by other transactions with table locks.
Step2: Determine whether each row in the table has been locked by row locks.
Pay attention to step2, this judgment method is really inefficient, because it needs to traverse the entire table.
So there is an intent lock.
When the intent lock exists, transaction A must first apply for the intent shared lock of the table, and then apply for the row lock of a row after success.
In the presence of intentional locks, the above judgment can be changed to
step1: unchanged
Step2: It is found that there is an intentional shared lock on the table, indicating that some rows in the table are locked by the shared row lock. Therefore, the write lock applied by transaction B to the table will be blocked.
Intention locks are designed to improve the efficiency of the blocking subsystem.
Note: The action of applying for the intention lock is completed by the database, that is, when transaction A applies for a row lock of a row, the database will automatically start to apply for the intention lock of the table first, and we do not need our programmers to use the code to apply .

Guess you like

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