C語言可重入函數和不可重入函數

【1】什麼是可重入函數和不可重入函數呢?

        可重入的函數:一般是保存在棧裡面的,是可以被編譯器隨機的分配記憶體並且釋放的函數稱為可重入函數

        不可重入函數:一般是指函數返回值是static 型的或者是函數內部定義了static變數或者使用了全局變數等稱為不可重入函數

 

【2】為什區分可重入和不可重入函數呢?

        因為多任務作業系統中,需要一個函數要滿足同時被多個任務調用,而且要確保每個任務都能單獨的維護自己的棧空間或者自身在記憶體暫存器中的值

 

【3】怎樣識別函數和不可重入函數呢?

  

/*This will either be
passed on the stack or in a CPU register. Either way is safe as
each task maintains its own stack and its own set of register
values. */

long int handler(int var1) { int var2; var2 = var1 + 2; return var2; } //可重入函數
 /* In this case lVar1 is a global variable so every task that calls
the function will be accessing the same single copy of the variable. */

long var1 long int handler(void) {
/* This variable is static so is not allocated on the stack. Each task
that calls the function will be accessing the same single copy of the
variable. */

static long state1 = 0; long 1Return; switch(state1) { case 0: 1Return = state1+10; state1 = 1; break; case 1: 1Return = state1+20; state1 = 0; break; } } //不可重入函數

 

Tags: