Mysql lock mechanism--concept, classification and basic commands

 

Mysql series article home page 

 

===============

 

1 Concept

In a Java program, when multiple threads access a resource concurrently, if there is a non-thread-safe operation, it needs to be protected by locking. Similarly, in Mysql, if there are multiple threads and multiple transactions concurrently accessing certain resources (such as writing the same row of records), locks are also required to protect the data to ensure the correctness of the data.

2 categories

According to the type of operation on the data:

  • Read lock (shared lock): For the same data, multiple read operations can be performed at the same time without affecting each other
  • Write lock (exclusive lock): other write and read operations will be blocked until the current write operation is completed

From the granularity of data operations:

  • Table lock: biased towards the MyISam engine, with low overhead and fast locking; no deadlock; large locking granularity, the highest probability of lock conflict, and the lowest degree of concurrency
  • Row lock: biased towards the InnoDB storage engine, high overhead, slow locking; deadlocks may occur; small locking granularity, the lowest probability of lock conflict, and the highest degree of concurrency

3 Basic commands

3.1 Check whether each table is locked or not in the current system:

SHOW OPEN TABLES;

Currently all In_use are 0, indicating that no table is locked. 

3.2 Add a read lock to the Employee table:

LOCK TABLE employee READ;

3.3 Add a write lock to the Department table:

LOCK TABLE department WRITE;

Alternatively, the 3.2 and 3.3 commands are written together like this:

LOCK TABLE employee READ, department WRITE;

3.4 Use SHOW OPEN TABLES to take a look

SHOW OPEN TABLES;

As you can see, the Employee and Department tables have been locked (In_use=1).

3.5 Unlock:

UNLOCK TABLES;

 Now, none of the tables are locked.

3.6 View table lock information on the system

SHOW STATUS LIKE 'table%';

This [Table_locks_waited] value is more important. The larger the value, the more times the lock is waited for and the greater the competition.

3.7 View the isolation level of the current database

SHOW VARIABLES LIKE 'tx_isolation';

This is the default isolation level of Mysql

3.8 InnoDB Engine View Lock Status

SHOW STATUS LIKE '%innodb_row_lock%';

The average waiting time, the total waiting time, and the total waiting times are three important items.

 

Guess you like

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