mysql死鎖示例

2021-07-11 18:44:43 字數 2758 閱讀 7149

mysql有三種鎖的級別:頁級、表級、行級。

myisam和memory儲存引擎採用的是表級鎖(table-level locking);bdb儲存引擎採用的是頁面鎖(page-level

locking),但也支援表級鎖;innodb儲存引擎既支援行級鎖(row-level locking),也支援表級鎖,但預設情況下是採用行級鎖。

mysql這3種鎖的特性可大致歸納如下:

表級鎖:開銷小,加鎖快;不會出現死鎖;鎖定粒度大,發生鎖衝突的概率最高,併發度最低。

行級鎖:開銷大,加鎖慢;會出現死鎖;鎖定粒度最小,發生鎖衝突的概率最低,併發度也最高。

頁面鎖:開銷和加鎖時間界於表鎖和行鎖之間;會出現死鎖;鎖定粒度界於表鎖和行鎖之間,併發度一般。

示例1:

-- 按行獲取行鎖

-- 獲取主鍵的共享鎖

insert into logging_exceptionlog_history_id_2 select * from logging_exceptionlog_history_id;

-- 獲取主鍵的互斥鎖

delete from logging_exceptionlog_history_id where id > 100 and id < 1000;

show engine innodb status;   檢視innodb引擎狀態,可檢視最近的死鎖情況

示例2:

表t1create table `t1` (

`id` int(11) not null auto_increment,

`name` varchar(64) default null,

`age` int(11) default null,

`posttime` timestamp null default current_timestamp on update current_timestamp,

primary key (`id`)

) engine=innodb auto_increment=2 default charset=utf8;

會話1-- 全域性的自動提交設為0,即不自動提交,然後另開乙個會話查詢autocommit狀態,當前會話可能還沒起作用

set global autocommit = 0;

會話2-- 另開乙個會話查詢autocommit狀態

show variables like '%autocommit%';

-- 插入一條記錄

insert into t1(name, age) values('***', 23);

會話3show variables like '%autocommit%';

-- 使用共享鎖查詢表,注意一定要加上 lock in share mode,否則不會出現死鎖

select * from t1 lock in share mode;   

檢視select * from innodb_lock_waits;

連線查詢, 只需要使用這個sql即可查詢上述三表的資訊

select a.requesting_trx_id, c.lock_mode as wait_lock_mode,

c.lock_type as wait_lock_type, c.lock_table as wait_lock_table,

c.lock_index as wait_lock_index, c.lock_data as wait_lock_data,

e.trx_state as wait_trx_state, e.trx_query as wait_trx_query,

a.blocking_trx_id,b.lock_mode as block_lock_mode, b.lock_type as block_lock_type,

b.lock_table as block_lock_table, b.lock_index as block_lock_index, b.lock_data as block_lock_data,

d.trx_state as block_trx_state, d.trx_query as block_trx_query

from information_schema.innodb_lock_waits a

inner join information_schema.innodb_locks b on a.blocking_lock_id = b.lock_id

inner join information_schema.innodb_locks c on a.requested_lock_id = c.lock_id

inner join information_schema.innodb_trx d on a.blocking_trx_id = d.trx_id

inner join information_schema.innodb_trx e on a.requesting_trx_id = e.trx_id

mysql 死鎖模擬 mysql死鎖示例

mysql有三種鎖的級別 頁級 表級 行級。myisam和memory儲存引擎採用的是表級鎖 table level locking bdb儲存引擎採用的是頁面鎖 page level locking 但也支援表級鎖 innodb儲存引擎既支援行級鎖 row level locking 也支援表級鎖...

python 死鎖 死鎖的示例 with

死鎖 死鎖就是一直等待對方釋放鎖的情景 死鎖的結果會造成程式的停止響應,不能再處理其他的任務了 需求 根據下標在列表中取值,保證同一時刻只能有乙個執行緒去取值 import threading import time 建立互斥鎖 lock threading.lock 根據下標去取值,保證同一時刻只...

python 執行緒死鎖示例

銀行轉賬 兩個賬戶同時給對方轉賬,模擬線程死鎖 from threading import thread,lock from time import sleep 賬戶類 class account def init self,id,balance,lock 每個賬戶自帶乙個鎖,只要數字balance...