如果你要查阅一个俗气的东西,你就上百度,如果要查稍微高级一点的东西,请上谷歌,当然英文的维基百科也不错。真的,我没有装逼。

      

      什么是可重入函数呢?先来看看维基百科的说明吧:

      In computing, a computer program or subroutine is called reentrant if it can be interrupted in the middle of its execution and then safely called again ("re-entered") before its previous invocations complete execution. The interruption could be caused by an internal action such as a jump or call, or by an external action such as ahardware interrupt or signal. Once the reentered invocation completes, the previous invocations will resume correct execution.

 

   我的理解是:可重入函数就是输入一定的情况下,输出结果必然固定, 而且从逻辑上讲要正确,不受任何其他情况的影响,所以,在我看来,随机函数也是不可重入的函数。当然,也欢迎提出不同的见解。

   一般来说,可重入函数要满足以下几个条件(至少要满足以下两个,当然还有更多的其他条件,此处不一一列举):

   1.不用全局变量,静态变量

   2.不调用不可重入函数(你调用了,自己就不可重入了,这个很好理解)

 

    下面我们分别来举例说明不可重入函数:

    没程序你说个鸟啊?没程序,搞点伪代码行不?为了不让你生气,我还是直接上代码:

 

#include<iostream>
using namespace std;

int n = 0;

int fun(int x)
{
	n++;
	return x + n;
}

int main()
{
	cout << fun(100) << endl; // 101
	cout << fun(100) << endl; // 102

	return 0;
}

   你看看,你看看,先后有两个童鞋调用了fun函数,而且传入的参数还是一样的,结果呢?结果,结果不一样。这就是不可重入函数的恶心之一。

 

 

   接着看程序,这个程序我之前写过了,现在直接复制过来:

 

#include <stdio.h>
#include <string.h>

void splitIntoTwoParts(char *org, char sep, char *left, char *right, int n)
{
	char delims[2] = {0};
	delims[0] = sep;
    char *result = strtok(org, delims); 
	strncpy(left, result, n - 1);
    while(result != NULL)
	{	
		result = strtok(NULL, delims);
		strncpy(right, result, n - 1);

		return;
    }
}

int main()
{
	char str[] = "a=1\nb=2\nc=3\nd=4\ne=5\nf=6";

	char left[100] = {0};
	char right[100] = {0};

    char delims[] = "\n";
    char *result = strtok(str, delims); 
    while(result != NULL)
	{	
		printf( "%s\n", result);
		splitIntoTwoParts(result, '=', left, right, 100);
		printf( "%s:%s\n", left, right);
		result = strtok(NULL, delims);	
    }

	return 0;
}

   你自己运行一下吧,反正得不到你从逻辑上分析的结果,这就是不可重入函数的恶心之二。
 

 

  一个函数如果是可重入的,就不怕你随便调用的,就不怕多线程这个SB任意摆弄了。所以,从这个意义上讲, 可重入函数一定是线程安全的。

 

  一幅图结束本文:

 


本文转载:CSDN博客