search
HomeDatabaseMysql TutorialWhat is the concept of mysql lock mechanism

What is the concept of mysql lock mechanism

Mysql lock:

To ensure the accuracy of data in a multi-threaded environment, it is usually necessary to use a synchronization mechanism. Synchronization is equivalent to locking. The purpose of the lock is that when one thread is operating data, other threads need to wait, which can bring the following benefits. When a thread completes execution, the lock is released. Only other threads can perform operations!

The function of the lock in our MySQL database is also similar. In the isolation of transaction processing, problems such as dirty reads, non-repeatable reads, and phantom reads may occur. Therefore, the role of locks can also be solved. these questions!

In a database, data is a resource shared and accessed by many users. How to ensure the consistency and effectiveness of concurrent data access is a problem that all databases must solve. Due to the characteristics of MySQL's own architecture, In different storage engines, locking mechanisms are designed to face specific scenarios. Therefore, the differences in engines lead to very different locking mechanisms.

Lock mechanism:

In order to ensure the consistency of data, the database uses a rule designed by using various shared resources to become orderly when accessed concurrently.

For example: When purchasing a product on an e-commerce website, there is only one product in the product list, and at this time two people are buying it at the same time, so who can buy it is a key issue.

Transactions will be used here to perform a series of operations:

First take out the item data from the product table

Then insert the order

After payment, Then insert the payment table information

Update the quantity of goods in the product table

In the above process, the lock can be used to protect the product quantity data information and achieve isolation, that is, only the first user is allowed to complete The entire purchase process, while other users can only wait, thus solving the conflict problem in concurrency.

Classification of locks:

Classification by operation:

Shared lock: also called read lock. Multiple transactions can read the same data at the same time and lock at the same time to avoid affecting each other, but they cannot modify the data records.

Exclusive lock: also called write lock. Before the current operation is completed, reading and writing of other operations will be blocked

Classified by granularity:

Table-level lock: During the operation, the entire operation will be locked surface. The overhead is small and locking is fast; deadlock will not occur; the locking force is strong, the probability of lock conflict is high, and the concurrency is the lowest. Prefer MyISAM storage engine!

Row-level lock: During operation, the current operation row will be locked. In the case of high concurrency, the locking granularity is small, which is beneficial to reducing the probability of lock conflicts, but attention must be paid to the speed of the locking operation to avoid excessive overhead, and the occurrence of deadlock must be avoided. Prefer InnoDB storage engine!

Page-level lock: The lock granularity, the probability of conflict, and the cost of locking are between table locks and row locks. Deadlocks will occur and concurrency performance is average.

Classification by usage:

Pessimistic lock: Every time you query the data, you think that others will modify it. It is very pessimistic, so you add a lock when querying.

Optimistic lock: Every time you query the data, you think that others will not modify it. You are very optimistic, but when updating, you will judge whether others have updated the data during this period.

Different storage engine support Lock

What is the concept of mysql lock mechanism

Shared lock:

Multiple shared locks can be shared. If there is a key, InnoDB defaults to a row lock. If not, it will Upgraded to table lock, when row lock is used, multiple windows can modify the data of different rows. If they are in the same row, they need to wait for the submission of the first lock. Different rows can be modified directly, but if the other one wants to query, it must wait for the submission of subsequent modifications. The lock disappears after submission

Shared lock:

SELECT语句 LOCK IN SHARE MODE;

Window 1:

- 窗口1
/*
    共享锁:数据可以被多个事务查询,但是不能修改
*/
-- 开启事务
START TRANSACTION;
-- 查询id为1的数据记录。加入共享锁
SELECT * FROM student WHERE id=1 LOCK IN SHARE MODE;
-- 查询分数为99分的数据记录。加入共享锁
SELECT * FROM student WHERE score=99 LOCK IN SHARE MODE;
-- 提交事务
COMMIT;

Window 2:

-- 窗口2
-- 开启事务
START TRANSACTION;
-- 查询id为1的数据记录(普通查询,可以查询)
SELECT * FROM student WHERE id=1;
-- 查询id为1的数据记录,并加入共享锁(可以查询。共享锁和共享锁兼容)
SELECT * FROM student WHERE id=1 LOCK IN SHARE MODE;
-- 修改id为1的姓名为张三三(不能修改,会出现锁的情况。只有窗口1提交事务后,才能修改成功)
UPDATE student SET NAME='张三三' WHERE id = 1;
-- 修改id为2的姓名为李四四(修改成功,InnoDB引擎默认是行锁)
UPDATE student SET NAME='李四四' WHERE id = 2;
-- 修改id为3的姓名为王五五(修改失败,InnoDB引擎如果不采用带索引的列加锁。则会提升为表锁)
UPDATE student SET NAME='王五五' WHERE id = 3;
-- 提交事务
COMMIT;

Exclusive lock:

When the exclusive lock is executed, other transactions can be queried normally, but no lock operations are allowed

-- 标准语法
SELECT语句 FOR UPDATE;

Window 1:

-- 窗口1
/*
    排他锁:加锁的数据,不能被其他事务加锁查询或修改
*/
-- 开启事务
START TRANSACTION;
-- 查询id为1的数据记录,并加入排他锁
SELECT * FROM student WHERE id=1 FOR UPDATE;
-- 提交事务
COMMIT;

Window 2:

-- 窗口2
-- 开启事务
START TRANSACTION;
-- 查询id为1的数据记录(普通查询没问题)
SELECT * FROM student WHERE id=1;
-- 查询id为1的数据记录,并加入共享锁(不能查询。因为排他锁不能和其他锁共存)
SELECT * FROM student WHERE id=1 LOCK IN SHARE MODE;
-- 查询id为1的数据记录,并加入排他锁(不能查询。因为排他锁不能和其他锁共存)
SELECT * FROM student WHERE id=1 FOR UPDATE;
-- 修改id为1的姓名为张三(不能修改,会出现锁的情况。只有窗口1提交事务后,才能修改成功)
UPDATE student SET NAME='张三' WHERE id=1;
-- 提交事务
COMMIT;

MyISAM lock:

MyISAM read lock:

MyISAM locks the entire table. When reading the lock, all transactions can be checked without unlocking, and no other operations, including its own transactions, are allowed. Operation

-- 加锁
LOCK TABLE 表名 READ;
-- 解锁(将当前会话所有的表进行解锁)
UNLOCK TABLES;

MyISAM write lock:

When writing the lock, other transactions cannot perform any operations as long as it is not unlocked. The own transaction can operate

-- 标准语法
-- 加锁
LOCK TABLE 表名 WRITE;
-- 解锁(将当前会话所有的表进行解锁)
UNLOCK TABLES;

Pessimistic lock :

is very pessimistic. It has a conservative attitude towards data being modified by the outside world and believes that the data will be modified at any time.

The data needs to be locked during the entire data processing. Pessimistic locking generally relies on the locking mechanism provided by relational databases.

Row locks and table locks are pessimistic locks regardless of whether they are read or write locks.

Optimistic locking:

is very optimistic. Every time you operate the data, you think no one will modify it, so you don’t lock it.

But when updating, it will be judged whether the data has been modified during this period.

Users need to implement it themselves. Concurrent resource preemption will not occur. Only when submitting the operation, the data integrity is checked for violation.

Simple implementation of optimistic locking:

Implementation idea: add markers to compare, if they are the same, they will be executed, if they are different, they will not be executed.

方式一:版本号

给数据表中添加一个version列,每次更新后都将这个列的值加1。

读取数据时,将版本号读取出来,在执行更新的时候,比较版本号。

如果相同则执行更新,如果不相同,说明此条数据已经发生了变化。

用户自行根据这个通知来决定怎么处理,比如重新开始一遍,或者放弃本次更新。

-- 创建city表
CREATE TABLE city(
    id INT PRIMARY KEY AUTO_INCREMENT,  -- 城市id
    NAME VARCHAR(20),                   -- 城市名称
    VERSION INT                         -- 版本号
);
-- 添加数据
INSERT INTO city VALUES (NULL,'北京',1),(NULL,'上海',1),(NULL,'广州',1),(NULL,'深圳',1);
-- 修改北京为北京市
-- 1.查询北京的version
SELECT VERSION FROM city WHERE NAME='北京';
-- 2.修改北京为北京市,版本号+1。并对比版本号
UPDATE city SET NAME='北京市',VERSION=VERSION+1 WHERE NAME='北京' AND VERSION=1;

方式二:时间戳

和版本号方式基本一样,给数据表中添加一个列,名称无所谓,数据类型需要是timestamp

每次更新后都将最新时间插入到此列。

读取数据时,将时间读取出来,在执行更新的时候,比较时间。

如果相同则执行更新,如果不相同,说明此条数据已经发生了变化。

悲观锁和乐观锁使用前提:

当读取操作远多于写操作时,更新操作被加锁会阻塞所有读取操作,降低了系统的吞吐量。最后还要释放锁,锁是需要一些开销的,这时候可以选择乐观锁。

如果是读写比例差距不是非常大或者系统没有响应不及时,吞吐量瓶颈的问题,那就不要去使用乐观锁,它增加了复杂度,也带来了业务额外的风险。这时候可以选择悲观锁。

The above is the detailed content of What is the concept of mysql lock mechanism. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
图文详解mysql架构原理图文详解mysql架构原理May 17, 2022 pm 05:54 PM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了关于架构原理的相关内容,MySQL Server架构自顶向下大致可以分网络连接层、服务层、存储引擎层和系统文件层,下面一起来看一下,希望对大家有帮助。

mysql的msi与zip版本有什么区别mysql的msi与zip版本有什么区别May 16, 2022 pm 04:33 PM

mysql的msi与zip版本的区别:1、zip包含的安装程序是一种主动安装,而msi包含的是被installer所用的安装文件以提交请求的方式安装;2、zip是一种数据压缩和文档存储的文件格式,msi是微软格式的安装包。

mysql怎么去掉第一个字符mysql怎么去掉第一个字符May 19, 2022 am 10:21 AM

方法:1、利用right函数,语法为“update 表名 set 指定字段 = right(指定字段, length(指定字段)-1)...”;2、利用substring函数,语法为“select substring(指定字段,2)..”。

mysql怎么替换换行符mysql怎么替换换行符Apr 18, 2022 pm 03:14 PM

在mysql中,可以利用char()和REPLACE()函数来替换换行符;REPLACE()函数可以用新字符串替换列中的换行符,而换行符可使用“char(13)”来表示,语法为“replace(字段名,char(13),'新字符串') ”。

mysql怎么将varchar转换为int类型mysql怎么将varchar转换为int类型May 12, 2022 pm 04:51 PM

转换方法:1、利用cast函数,语法“select * from 表名 order by cast(字段名 as SIGNED)”;2、利用“select * from 表名 order by CONVERT(字段名,SIGNED)”语句。

MySQL复制技术之异步复制和半同步复制MySQL复制技术之异步复制和半同步复制Apr 25, 2022 pm 07:21 PM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了关于MySQL复制技术的相关问题,包括了异步复制、半同步复制等等内容,下面一起来看一下,希望对大家有帮助。

mysql怎么判断是否是数字类型mysql怎么判断是否是数字类型May 16, 2022 am 10:09 AM

在mysql中,可以利用REGEXP运算符判断数据是否是数字类型,语法为“String REGEXP '[^0-9.]'”;该运算符是正则表达式的缩写,若数据字符中含有数字时,返回的结果是true,反之返回的结果是false。

带你把MySQL索引吃透了带你把MySQL索引吃透了Apr 22, 2022 am 11:48 AM

本篇文章给大家带来了关于mysql的相关知识,其中主要介绍了mysql高级篇的一些问题,包括了索引是什么、索引底层实现等等问题,下面一起来看一下,希望对大家有帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.