V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
MySQL 5.5 Community Server
MySQL 5.6 Community Server
Percona Configuration Wizard
XtraBackup 搭建主从复制
Great Sites on MySQL
Percona
MySQL Performance Blog
Severalnines
推荐管理工具
Sequel Pro
phpMyAdmin
推荐书目
MySQL Cookbook
MySQL 相关项目
MariaDB
Drizzle
参考文档
http://mysql-python.sourceforge.net/MySQLdb.html
Rosicky
V2EX  ›  MySQL

MyISAM 表锁的优先级问题

  •  
  •   Rosicky · 2016-07-13 22:07:35 +08:00 · 1988 次点击
    这是一个创建于 2845 天前的主题,其中的信息可能已经有所发展或是发生改变。
    想验证 myisam 表的锁的优先级,做了下面的实验。使用的测试表,结构如下
    mysql> show create table tx\G
    *************************** 1. row ***************************
    Table: tx
    Create Table: CREATE TABLE `tx` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `num` int(11) DEFAULT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8


    然后分别打开打开三个控制台 ABC ,按下面操作顺序执行:

    1 、 A 运行:
    mysql> lock table tx read;
    Query OK, 0 rows affected (9 min 37.73 sec)

    2 、 B 运行:
    mysql> select * from tx;
    这里在等待

    3 、 C 运行:
    mysql> insert into tx (num) value (1);
    这里在等待

    4 、 A 运行:
    mysql> unlock tables;
    Query OK, 0 rows affected (0.00 sec)

    此时看控制台 B ,显示
    mysql> select * from tx;
    Empty set (1 min 25.67 sec)

    这里有个疑惑,写锁不是会插到读锁请求之前吗?但是显式的给 B 、 C 加上 lock 语句,就可以看到 C (写)先获得锁。
    这是为什么呢?
    3 条回复    2016-07-14 00:16:43 +08:00
    yangqi
        1
    yangqi  
       2016-07-13 22:13:29 +08:00   ❤️ 1
    "WRITE locks normally have higher priority than READ locks to ensure that updates are processed as soon as possible. This means that if one session obtains a READ lock and then another session requests a WRITE lock, subsequent READ lock requests wait until the session that requested the WRITE lock has obtained the lock and released it.

    LOCK TABLES acquires locks as follows:

    1.Sort all tables to be locked in an internally defined order. From the user standpoint, this order is undefined.

    2.If a table is to be locked with a read and a write lock, put the write lock request before the read lock request.

    3.Lock one table at a time until the session gets all locks."
    Rosicky
        2
    Rosicky  
    OP
       2016-07-13 23:26:37 +08:00
    手动加锁和自动加锁有什么区别?
    Rosicky
        3
    Rosicky  
    OP
       2016-07-14 00:16:43 +08:00
    贴下另一组测试,顺序运行

    1 、 A 运行:
    mysql> lock table tx read;
    Query OK, 0 rows affected (9 min 37.73 sec)

    2 、 B 运行:
    mysql> lock table tx read;
    这里在等待

    3 、 C 运行:
    mysql> lock table tx write;
    这里在等待

    4 、 A 运行:
    mysql> unlock tables;
    Query OK, 0 rows affected (0.00 sec)

    此时看控制台 C 已获得锁, B 等待。这个结果就和文档一样
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3396 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 10:58 · PVG 18:58 · LAX 03:58 · JFK 06:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.