高效編程之互斥鎖和自旋鎖的一些知識


兩種鎖的加鎖原理

互斥鎖:線程會從sleep(加鎖)——>running(解鎖),過程中有上下文的切換,cpu的搶占,信號的發送等開銷。

自旋鎖:線程一直是running(加鎖——>解鎖),死循環檢測鎖的標志位,機制不復雜。

兩種鎖的區別

互斥鎖的起始原始開銷要高於自旋鎖,但是基本是一勞永逸,臨界區持鎖時間的大小並不會對互斥鎖的開銷造成影響,而自旋鎖是死循環檢測,加鎖全程消耗cpu,起始開銷雖然低於互斥鎖,但是隨着持鎖時間,加鎖的開銷是線性增長。

兩種鎖的應用

互斥鎖用於臨界區持鎖時間比較長的操作,比如下面這些情況都可以考慮

1 臨界區有IO操作

2 臨界區代碼復雜或者循環量大

3 臨界區競爭非常激烈

4 單核處理器

至於自旋鎖就主要用在臨界區持鎖時間非常短且CPU資源不緊張的情況下。

自旋-互斥鎖

下面的英文介紹了混合互斥鎖和混合自旋鎖,但是不管是第一段說的先上非阻塞鎖后上阻塞鎖,還是第二段說的先自旋上鎖后進行休眠,反正思路都是先自旋上鎖一定時間后在上互斥鎖,這種自旋-互斥鎖適合各線程持鎖時間間隔跨度比較大的情況。

A hybrid mutex behaves like a spinlock at first on a multi-core system. If a thread cannot lock the mutex, it won't be put to sleep immediately, since the mutex might get unlocked pretty soon, so instead the mutex will first behave exactly like a spinlock. Only if the lock has still not been obtained after a certain amount of time (or retries or any other measuring factor), the thread is really put to sleep. If the same system runs on a system with only a single core, the mutex will not spinlock, though, as, see above, that would not be beneficial.

A hybrid spinlock behaves like a normal spinlock at first, but to avoid wasting too much CPU time, it may have a back-off strategy. It will usually not put the thread to sleep (since you don't want that to happen when using a spinlock), but it may decide to stop the thread (either immediately or after a certain amount of time) and allow another thread to run, thus increasing chances that the spinlock is unlocked (a pure thread switch is usually less expensive than one that involves putting a thread to sleep and waking it up again later on, though not by far).


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM