volatile 和 sig_atomic_t
a. volatile是C語言定義的關鍵字,gcc為了需要又定義了__volatile__,它和
volatile表達的是同一意思。
b. volatile的本意是"易變的",由于訪問寄存器的速度快于訪存,所以編譯器一般
都會作優化以減少訪存。如果變量加上volatile修飾,則編譯器就不會對此變量
的讀寫操作進行優化,即不通過寄存器緩沖而直接訪存。
c. __asm__ __volatile__一起指示編譯器不要改動優化后面的匯編語句。 3).sig_atomic_t: 當把變量聲明為該類型是,則會保證該變量在使用或賦值時, 無論是在32位還是64位的機器上都能保證操作是原子的,它會根據機器的類型自動適應。 今天看源代碼時,看到sig_atomic_t這個類型,平時用得較少,平時一般是用int類型來代替。 這個類型是定義在signal.h文件中。下面來說說這個類型。 在處理信號(signal)的時候,有時對于一些變量的訪問希望不會被中斷,無論是硬件中 斷還是軟件中斷,這就要求訪問或改變這些變量需要在計算機的一條指令內完成。通常情況下,int類型的變量通常是原子訪問的,也可以認為 sig_atomic_t就是int類型的數據,因為對這些變量要求一條指令完成,所以sig_atomic_t不可能是結構體,只會是數字類型。 在linux里這樣定義: typedef int __sig_atomic_t; 另外gnu c的文檔也說比int短的類型通常也是具有原子性的,例如short類型。同時,指針(地址)類型也一定是原子性的。 該類型在所有gnu c庫支持的系統和支持posix的系統中都有定義。 注:關于int型是不是原子的操作,看下面的gnu文檔
http://www.gnu.org/s/hello/manual/libc/Atomic-Types.html
24.4.7.2 Atomic Types
To avoid uncertainty about interrupting access to a variable, you can use a particular data type for which access is always atomic:?sig_atomic_t. Reading and writing this data type is guaranteed to happen in a single instruction, so there's no way for a handler to run “in the middle” of an access.
The type?sig_atomic_t?is always an integer data type, but which one it is, and how many bits it contains, may vary from machine to machine.
— Data Type:?sig_atomic_tThis is an integer data type. Objects of this type are always accessed atomically.
In practice, you can assume that?int?is atomic. You can also assume that pointer types are atomic; that is very convenient. Both of these assumptions are true on all of the machines that the GNU C library supports and on all POSIX systems we know of.轉載于:https://www.cnblogs.com/hengli/archive/2012/12/14/2818343.html
總結
以上是生活随笔為你收集整理的volatile 和 sig_atomic_t的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java 将excel中的内容导入数据库
- 下一篇: 返回顶部 js