關於互斥鎖

2021-08-11 16:19:18 字數 1562 閱讀 3748

顧名思義,在多執行緒下,用來鎖定資源使用許可權。

我們先看一段**:

#include#include#include#includeint count =0;

void *func(void* argc)

pthread_exit(null);
return null; 

}int main()

t1 t2兩個執行緒可以同時修改count,所以很難得到我們希望的結果。

[before] tid:1845761792 count:0

[after] tid:1845761792 count:1

[before] tid:1845761792 count:1

[after] tid:1845761792 count:2

[before] tid:1845761792 count:2

[before] tid:1837369088 count:0

[after] tid:1837369088 count:4

[before] tid:1837369088 count:4

[after] tid:1837369088 count:5

[before] tid:1837369088 count:5

[after] tid:1837369088 count:6

[after] tid:1845761792 count:3

如果希望乙個執行緒在修改資源時,其他執行緒無法獲取資源的修改權時,可以使用互斥鎖來實現。

修改一下**:

#include#include#include#includeint count =0;
pthread_mutex_t mutex;
void *func(void* argc)

pthread_exit(null);
return null; 

}int main()

結果:[before] tid:806139648 count:0

[after] tid:806139648 count:1

[before] tid:806139648 count:1

[after] tid:806139648 count:2

[before] tid:806139648 count:2

[after] tid:806139648 count:3

[before] tid:797746944 count:3

[after] tid:797746944 count:4

[before] tid:797746944 count:4

[after] tid:797746944 count:5

[before] tid:797746944 count:5

[after] tid:797746944 count:6

互斥鎖機制,互斥鎖與讀寫鎖區別

互斥鎖 mutex,用於保證在任何時刻,都只能有乙個執行緒訪問該物件。當獲取鎖操作失敗時,執行緒會進入睡眠,等待鎖釋放時被喚醒 讀寫鎖 rwlock,分為讀鎖和寫鎖。處於讀操作時,可以允許多個執行緒同時獲得讀操作。但是同一時刻只能有乙個執行緒可以獲得寫鎖。其它獲取寫鎖失敗的執行緒都會進入睡眠狀態,直...

鎖 互斥鎖,死鎖

當多個執行緒幾乎同時修改某乙個共享資料的時候,需要進行同步控制 執行緒同步能夠保證多個執行緒安全訪問競爭資源,最簡單的同步機制是引入互斥鎖。互斥鎖為資源引入乙個狀態 鎖定 非鎖定 某個執行緒要更改共享資料時,先將其鎖定,此時資源的狀態為 鎖定 其他執行緒不能更改 直到該執行緒釋放資源,將資源的狀態變...

關於執行緒注意點和互斥鎖

執行緒同步能夠保證多個執行緒安全訪問競爭資源,最簡單的同步機制是引入互斥鎖。互斥鎖為資源引入乙個狀態 鎖定 非鎖定。某個執行緒要更改共享資料時,先將其鎖定,此時資源的狀態為 鎖定 其他執行緒不能更改 直到該執行緒釋放資源,將資源的狀態變成 非鎖定 其他的執行緒才能再次鎖定該資源。互斥鎖保證了每次只有...