如果一个函数可以安全地被多个任务调用,或是在任务与中断中均可调用,则这个
函数是
可重入的。
每个任务都单独维护自己的栈空间及其自身在的内存寄存器组中的值。
如果一个函
数除了访问自己栈空间上分配的数据或是内核寄存器中的数据外,不会访问其它任何
数据,则这个函数就是
可重入的。
-
-
可重入函数示例
-
/* A parameter is passed into the function. 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 lAddOneHundered( long lVar1 )
-
{
-
/* This function scope variable will also be allocated to the stack
-
or a register, depending on compiler and optimization level. Each
-
task or interrupt that calls this function will have its own copy
-
of lVar2. */
-
long lVar2;
-
lVar2 = lVar1 + 100;
-
-
/* Most likely the return value will be placed in a CPU register,
-
although it too could be placed on the stack. */
-
return lVar2;
-
}
-
-
2.不可重入函数示例
-
/* 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 lVar1;
-
long lNonsenseFunction( 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 lState = 0;
-
long lReturn;
-
-
switch( lState )
-
{
-
case 0 : lReturn = lVar1 + 10;
-
lState = 1;
-
break;
-
-
case 1 : lReturn = lVar1 + 20;
-
lState = 0;
-
break;
-
}
-
}
阅读(866) | 评论(0) | 转发(0) |