x86的cpu_relax解析

來源:互聯網
上載者:User

原文:http://blog.liuw.name/1024

核心執行的任務在很多情況下是不加鎖的,只是poll某個公有變數去保證同步。再深一步,即使是使用鎖,本質上也是一個poll某個公有變數的過程。這個poll的過程需要CPU一直迴圈等待。

要是讓我這個菜鳥來寫的話,迴圈體內大概是什麼都不會做的了,XD。而x86的核心中一般是調用cpu_relax()。這個函數又是何方神聖呢?

實際上,這個函數很簡單。

?
12345 #define cpu_relax() rep_nop()static always_inline void rep_nop(void){        asm volatile ( "rep;nop" : : : "memory" );}

自旋鎖裡面也有rep;nop這個語句。而我很蛋痛地在想,為什麼是rep;nop而不是nop;nop而不是nop;nop;nop…;nop,反正都是什麼都不做嘛,為什麼偏偏要選這個?眾所周知,在核心這個層次,基本上每一行代碼都是最優的,做出這樣的選擇必定事出有因。

rep;nop的機器碼是f3 90,其實就是pause指令的機器碼,相當於pause的一個“別名”,這是巧合嗎?pause指令又是幹什麼的呢?

從Intel的手冊裡面翻出來一段話:

Improves the performance of spin-wait loops. When executing a “spin-wait loop,” a Pentium 4 or Intel Xeon processor suffers a severe performance penalty when exiting the loop because it detects a possible memory order violation. The PAUSE instruction provides a hint to the processor that the code sequence is a spin-wait loop. The processor uses this hint to avoid the memory order violation in most situations, which greatly improves processor performance. For this reason, it is recommended that a PAUSE instruction be placed in all spin-wait loops.

An additional fucntion of the PAUSE instruction is to reduce the power consumed by a Pentium 4 processor while executing a spin loop.

簡單點說,用pause可以提示CPU接下來的指令序列是用來自旋等待,就不用做memory reorder了,cache什麼的也不用廢掉了——要知道,cache是很寶貴的資源啊。這指令還有附送的功能——減少能耗。其實核心代碼最根本的要求就是:快,快,更加快,這條指令還有附送功能,所以何樂而不為呢?

那麼為什麼不直接寫pause而要寫rep;nop呢?理論上是等價的,但是實際上為什麼不這樣做,不好意思,不清楚。但是可以確定是的pause是Pentium 4才引入的,也許大家比較懷舊所以還用rep;nop也說不定。

So,以後寫應用程式而又蛋痛寫了迴圈等待的話,不妨也用用pause吧。不過我想會在應用程式中寫迴圈等待這麼傻的代碼的程式員,應該也想不到用pause去節能減排兼提速了吧,傷腦筋。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.