PostgreSQL之死鎖模擬

2021-09-26 05:53:35 字數 2017 閱讀 4319

1.什麼是死鎖

多個程序競爭資源,a程序占用了一部分資源,又去申請其他資源,a程序申請的資源被b程序占用, b程序申請a資源占用的資源,這樣就形成了死鎖。

2.產生死鎖的條件是什麼

1⃣️互斥 2⃣️占有並等待 3⃣️ 非剝奪 4⃣️迴圈等待

3.解決死鎖的方法

1⃣️預防死鎖 通過破壞死鎖產生的條件一致 ->效率低

2⃣️避免死鎖 通過安全性演算法計算資源的分配 ->效率低

3⃣️檢測並解除死鎖 現在常用的

1.建表

create table a (id int primary key,info timestamp);

create table

2.插入資料

test=# insert into a select generate_series(1,10);

insert 0 10

3.開啟兩個會話 分別執行

會話1 執行sql

test=#  update a set info =clock_timestamp() from (values(1),(2))t(id) where a.id = t.id and pg_sleep(1) is not null;
會話2 馬上執行sql

test=#  update a set info =clock_timestamp() from (values(2),(1))t(id) where a.id = t.id and pg_sleep(1) is not null;    

2019-08-16 14:12:33.978 cst [7880] error: deadlock detected

2019-08-16 14:12:33.978 cst [7880] detail: process 7880 waits for sharelock on transaction 1861043; blocked by process 7951.

process 7951 waits for sharelock on transaction 1861042; blocked by process 7880.

process 7880: update a set info =clock_timestamp() from (values(2),(1))t(id) where a.id = t.id and pg_sleep(2) is not null;

process 7951: update a set info =clock_timestamp() from (values(1),(2))t(id) where a.id = t.id and pg_sleep(2)is not null;

2019-08-16 14:12:33.978 cst [7880] hint: see server log for query details.

2019-08-16 14:12:33.978 cst [7880] context: while updating tuple (0,21) in relation "a"

2019-08-16 14:12:33.978 cst [7880] statement: update a set info =clock_timestamp() from (values(2),(1))t(id) where a.id = t.id and pg_sleep(2) is not null;

error: deadlock detected

detail: process 7880 waits for sharelock on transaction 1861043; blocked by process 7951.

process 7951 waits for sharelock on transaction 1861042; blocked by process 7880.

hint: see server log for query details.

context: while updating tuple (0,21) in relation "a"

執行緒同步之死鎖

public class stateobject i public void deadlock2 i stateobject state1 new stateobject stateobject state2 new stateobject new thread new samplethread s...

程序管理之死鎖

前面兩篇部落格 1.程序同步之臨界區域問題及peterson演算法 2.程序同步之訊號量機制 pv操作 及三個經典同步問題 介紹了程序管理中程序同步的諸多問題,下面為大家詳細解讀程序管理中死鎖的問題及其解決方案。在多道程式設計環境下,多個程序可能競爭一定數量的資源。乙個程序申請資源,如果資源不可用,...

執行緒同步之死鎖

什麼是死鎖呢?死鎖就是多個程序或者執行緒訪問同乙個資源的時候,誰也搶不到資源,誰也不退讓讓其他程序或者執行緒訪問,使用者看到的就是程式卡住了。舉個例子吧,在乙個沒有紅綠燈的十字路口,來了四輛小汽車,每個路口都只能讓乙個汽車通過。現在這種情況四輛車都過不了汽車,這就發生了死鎖。發生死鎖的原因?第一種情...