MySQL/MariaDB数据库的并发控制

                            作者:尹正杰 

版权声明:原创作品,谢绝转载!否则将追究法律责任。

 

 

一.并发控制概述

1>.什么是并发控制

  MySQL是一个服务器级别的数据库,它通常放在网络上有很多用户并发访问的,因此并发控制很关键。

2>.锁粒度

  表级锁(MyISAM和Innodb都支持) 

  行级锁(仅Innodb支持,MyISAM不支持)

3>.锁

  读锁:
    共享锁,只读不可写(包括当前事务) ,多个读互不阻塞
  写锁:
    独占锁,排它锁,写锁会阻塞其它事务(不包括当前事务)的读和它锁

4>.实现

  存储引擎:
    自行实现其锁策略和锁粒度
  服务器级:实现了锁,表级锁,用户可显式请求

5>.分类

  隐式锁:
    由存储引擎自动施加锁
  显式锁:
    用户手动请求

6>.锁策略

  在锁粒度及数据安全性寻求的平衡机制

7>.死锁

  两个或多个事务在同一资源相互占用,并请求锁定对方占用的资源的状态

 

二.针对表级别显式使用锁实战案例

1>.查看锁帮助信息

MariaDB [yinzhengjie]> HELP LOCK 
Name: 'LOCK'
Description:
Syntax:
LOCK TABLES
    tbl_name [[AS] alias] lock_type
    [, tbl_name [[AS] alias] lock_type] ...

lock_type:
    READ [LOCAL]
  | [LOW_PRIORITY] WRITE

UNLOCK TABLES

MySQL enables client sessions to acquire table locks explicitly for the
purpose of cooperating with other sessions for access to tables, or to
prevent other sessions from modifying tables during periods when a
session requires exclusive access to them. A session can acquire or
release locks only for itself. One session cannot acquire locks for
another session or release locks held by another session.

Locks may be used to emulate transactions or to get more speed when
updating tables. This is explained in more detail later in this
section.

LOCK TABLES explicitly acquires table locks for the current client
session. Table locks can be acquired for base tables or views. You must
have the LOCK TABLES privilege, and the SELECT privilege for each
object to be locked.

For view locking, LOCK TABLES adds all base tables used in the view to
the set of tables to be locked and locks them automatically. If you
lock a table explicitly with LOCK TABLES, any tables used in triggers
are also locked implicitly, as described in
https://mariadb.com/kb/en/triggers-and-implicit-locks/.

UNLOCK TABLES explicitly releases any table locks held by the current
session. LOCK TABLES implicitly releases any table locks held by the
current session before acquiring new locks.

Another use for UNLOCK TABLES is to release the global read lock
acquired with the FLUSH TABLES WITH READ LOCK statement, which enables
you to lock all tables in all databases. See [HELP FLUSH]. (This is a
very convenient way to get backups if you have a file system such as
Veritas that can take snapshots in time.)

URL: https://mariadb.com/kb/en/transactions-lock/


MariaDB [yinzhengjie]> 
MariaDB [yinzhengjie]> HELP LOCK

相关文章: