close
參考出處: volatile  1  2
 
compiler 的最佳化編譯,為了增快程式速度,
有時候會很聰明的將程式碼編譯成和原 code 不同,但意思相同的 object code
如下:
for (int i = 0; i < 10000; i++) {
    a = 5;
   a =  a * i;
}
compiler 可以簡化成下列一條敘述:
a = 5 * 9999;
編譯器最佳化,就讓程式變得更有效率。
 
但是當我們某些程式片段不希望做最佳化的時候呢? 就要使用 volatile 關鍵字
volatile 是 C 的關鍵字,用來修飾資料型態,是告訴 compiler 不要對這一個變數的程式碼區段做最佳化。
通常是用在有 multiple threads without using the lock Statement 的時候,
因為這個變數值有可能常常會被外在 routine 改變(在kernel裡面通常是指 interrupt handler )
舉例來說
Volatile char wait;
void xxx(void){
  wait=1;
  while (wait==0);
  .....
  .....
}
void timer0(void) interrupt 1{
  wait=0;
  .......
}
xxx() 中就是等一個 timer 中斷才會執行底下的工作
如果不寫 Volatile 會被編譯器省略掉,因為 wait=1,來 wait  會等於 0

restrict 是 C 的關鍵字,只能用來修飾 pointer,目的是協助 compiler 做最佳化
是告知 compiler ,這一個 restrict pointer 是唯一指向 data 的 pointer,
意即程式當中不會透過其他變數 ( pointer,或者直接存取 ) 來 access 此 data,
例子如下:
int * restrict rptr = (int*) malloc(10*sizeof(int));
int a[10];
int * ptr;
ptr = a;
for(int i =0; i<10;i++) { 
    ptr += 5;
    rptr +=5;
    a *= 5;
    ptr += 3;
    rptr += 3;
}
當 compiler 看到 rptr 為 restric,就會用 rptr += 8 取代 rptr += 3 和 rptr += 5
而 ptr 就不應該被直接替換,因為它不是唯一會 access 該 data 的變數
 
C99 用到restrict的例子:
void* memcpy (void* restrict destination, const void* restrict source, size_t n);
代表destination和source區段是不可重疊的
 
FILE *fopen(const char *restrict pathname, const char *restrict type);
arrow
arrow
    全站熱搜

    Y CP 發表在 痞客邦 留言(0) 人氣()