mysql鎖

在做大型并發(fā)的業(yè)務(wù)的時候,mysql的鎖對整個程序的正確運行和高效運行都有很重要的作用。這次研究的mysql的鎖的機制,現(xiàn)將代碼記錄下參考(線程一的執(zhí)行序號對應(yīng)線程二的執(zhí)行序號):

線程一的幾個操作

-- 【1】
-- 加表級別的寫鎖
-- LOCK TABLES tb_volunteer write;
-- UNLOCK TABLES; -- 最后在執(zhí)行

-- 【2】
-- 事務(wù)中的鎖【更新】
set autocommit  = 0;
begin;
update tb_volunteer set nation='回族' where user_id = 75;
commit; -- 最后執(zhí)行

-- 【3】
-- 事務(wù)中的排他鎖【查詢】
set autocommit = 0;
begin work;
select * from tb_volunteer where user_id = 75 for update; -- 僅自己更新,其他可以查詢,更新阻塞
commit work;

-- 【4】
-- 事務(wù)中的共享鎖
set autocommit = 0;
begin;
SELECT * from tb_volunteer where user_id = 75 LOCK IN SHARE MODE; -- 僅多人查詢,誰都不能更新
commit;

-- 聚合中的鎖【5】
-- 實際上是一個表鎖了
set autocommit =0;
begin;
select max(code) from tb_volunteer where age_group = 1 for update ;
update tb_volunteer set nation='壯族' where user_id = 75;
commit;

-- 【6】
-- 行鎖在非索引字段時候可否
-- 即使條件字段不是索引字段,也可以上鎖
set autocommit=0;
begin;
select * from tb_volunteer where id = 215 for update;
commit;

-- 【7】
-- 查詢時候不加特殊條件是否阻塞
set autocommit = 0;
begin;
select * from tb_volunteer where id = 211;
commit; -- 最后執(zhí)行




線程二對應(yīng)(序號)的幾個操作

-- 【1】
-- 若不解表鎖一直阻塞
select * from tb_volunteer;

-- 【2】
-- 不commit提交事務(wù)不同線程阻塞,commit后其他線程可繼續(xù)
update tb_volunteer set nation='壯族' where user_id = 25;

-- 【3】
-- 不commit提交事務(wù)他人阻塞,同線程可改,commit后其他線程繼續(xù)
update tb_volunteer set nation='維吾爾族' where user_id = 75;

-- 【4】
-- 再次嘗試了下,感覺和for update差別不大,別人線程都是只能讀,不能寫,自己線程能讀能寫
select * from tb_volunteer where user_id = 75; -- 【可直接執(zhí)行】
update tb_volunteer set nation='彝族' where user_id = 75; -- 【commit之后才能執(zhí)行】

-- 【5】
-- 聚合上鎖研究
select * from tb_volunteer where age_group = 1
update tb_volunteer set nation='漢族' where user_id >75 and age_group = 2 ;

-- 【6】
-- 行鎖在非索引字段時候可否【6】:可
update tb_volunteer set nation='藏族' where id = 215;

-- 【7】
-- 查詢時候即使沒有commit,也能更新
update tb_volunteer set nation = '壯族' where id = 211
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容