在关系型数据库内,事务是由一个SQL或一组SQL语句组成的逻辑处理单元。也就是说事务就相当于一个盛放SQL的容器,事务中的SQL要么全部执行成功,要么所有已经修改的操作都回滚到原来的操作,即一条SQL也不能执行成功。
事务的四大特性(ACID):
隐式==自动
显式==手动
在高并发场景中,多个并发事务操作相同的数据,一些奇怪的现象是数据不安全的表现。
[En]
In a high concurrency scenario, multiple concurrent transactions operate the same data, and some strange phenomena are a manifestation of data insecurity.
锁是一种确保数据安全的机制,即协调多个进程或线程并发访问一个资源。
[En]
Lock is a mechanism to ensure data security, that is, to coordinate multiple processes or threads to access a resource concurrently.
以互斥为例,一次只能运行多个并发任务中的一个,以牺牲效率来保证数据安全。
[En]
Take mutex as an example, so that only one of multiple concurrent tasks can be run at a time, sacrificing efficiency for data security.
锁的优缺点:
- 优势:确保并发场景下的数据安全。
[En]
advantage: ensuring the security of data in concurrent scenarios.*
- 缺点:降低了效率。
因此,在使用锁时,应尽可能缩小锁的范围,即锁定的数据越小越好,并发能力越高。
[En]
Therefore, when using the lock, we should narrow the scope of the lock as much as possible, that is, the smaller the locked data, the better, the higher the concurrency ability.
锁的分类:
按粒度分类:行级锁、表级锁、页级锁。
[En]
Classified by granularity: row-level lock, table-level lock, page-level lock.
按级别分类:共享锁、排他锁。
[En]
Classified by level: shared lock, exclusive lock.
按使用方式分类:乐观锁(当我更改数据时,没有人在修改和我相同的数据,也可以说它本身不是锁,因为它是从程序的角度编写程序的例程。本质上,没有锁),悲观锁(在我的事务中,当我更改数据时,我总是认为肯定有人在抢我悲观锁通常是使用数据内置的锁定机制实现的)
[En]
Classified by way of use: optimistic lock (no one is modifying the same data as me when I change the data, it can also be said that it is not a lock itself, because it is a routine of writing a program from a program point of view. Essentially, there is no lock), pessimistic lock (in my affairs, when I change the data, I always think that someone must be robbing me Pessimistic locks are usually implemented using the data-built-in locking mechanism)
行级锁:
行级锁它分为共享锁,排他锁,是MySQL中粒度最细的一种锁,所以它的并发能力也是最高的。
对于insert、update、delete语句、innodb会自动给涉及的数据加锁,而且是排他锁;
对于普通的select语句,innodb不会加任何锁,需要手动自己加,可以加两种类型的锁;
--共享锁(s):能同时加到锁和抢到锁的是多个,保障读的一致性
select * from 表名 where ... lock in share mode;
--排他锁(x):同一时间只能有一个能抢到,保障写数据的安全
select * from 表名 where ... for update;
锁的使用:例如
1、事务A对id=3的行加了互斥锁后,其他事务对id=3的行不能加任何锁(写不行,但是可以读)
2、事务A对id=3的行加了共享锁后,其他事务对id=3的行只能加共享锁,或者不加锁(写不行,但可以读)
表级锁:
表级锁是MySQL中粒度最大的一种锁,整张表都被加锁,当然并发能力也是最低的。
lock table 表名 read(write),表名 read(write),.........;
--SQL语句
unlock tables; -->释放当前会话持有的任何锁
页级锁:
页锁是介于表锁和行锁之间的一种锁,粒度介于表锁和行锁之间,并发能力一般。
[En]
Page lock is a kind of lock between table lock and row lock, the granularity is between table lock and row lock, and the concurrency ability is general.
Original: https://www.cnblogs.com/XiaoYang-sir/p/15866057.html
Author: Mr-Yang`
Title: MySQL事务与锁
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/507836/
转载文章受原作者版权保护。转载请注明原作者出处!