日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

高效编程之互斥锁和自旋锁

發布時間:2025/5/22 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 高效编程之互斥锁和自旋锁 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

兩種鎖的加鎖原理

互斥鎖:線程會從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).

轉自:http://www.cnblogs.com/hdflzh/p/3716156.html

轉載于:https://www.cnblogs.com/colife/p/5420054.html

總結

以上是生活随笔為你收集整理的高效编程之互斥锁和自旋锁的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。