可重入 (Reentrancy) 和 线程安全 (Thread-Safe)

15 篇文章 0 订阅

wiki: http://en.wikipedia.org/wiki/Reentrancy_%28computing%29


wiki上讲的很清楚了。

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 a hardware interrupt or signal. Once the reentered invocation completes, the previous invocations will resume correct execution.

This definition originates from single-threaded programming environments where the flow of control could be interrupted by ahardware interrupt and transferred to an interrupt service routine (ISR). Any subroutine used by the ISR that could potentially have been executing when the interrupt was triggered should be reentrant. Often, subroutines accessible via the operating systemkernel are not reentrant. Hence, interrupt service routines are limited in the actions they can perform; for instance, they are usually restricted from accessing the file system and sometimes even from allocating memory.

A subroutine that is directly or indirectly recursive should be reentrant. This policy is partially enforced bystructured programming languages.[citation needed] However a subroutine can fail to be reentrant if it relies on aglobal variable to remain unchanged but that variable is modified when the subroutine is recursively invoked.

This definition of reentrancy differs from that of thread-safety in multi-threaded environments. A reentrant subroutine can achieve thread-safety,[1] but being reentrant alone might not be sufficient to be thread-safe in all situations. Conversely, thread-safe code does not necessarily have to be reentrant (see below for examples).

使用了全局变量,不可重入:

int g_var = 1;
 
int f()
{
 g_var = g_var + 2;
 return g_var;
}
 
int g()
{
 return f() + 2;
}

函数 f() , g() 都是不可重入的。因为f()中使用了全局变量。如果多个进程并发,执行f()时, g_var的值是不确定的。


可重入的代码:

int f(int i)
{
 return i + 2;
}
 
int g(int i)
{
 return f(i) + 2;
}

============可重入(reentrant)和  线程安全(thread-safe)===============

参考: http://blog.csdn.net/xiaofei0859/article/details/5818511


什么函数是可重入的?

一个函数在被调用结束前,可以再次在其他地方被正确的调用,这样的函数是可重入的。

想像一个这样的场景:

一个程序正在调用函数func时(调用还没有返回),被某信号中断,然后在信号处理程序中再次调用了函数func。

如果函数func是不可重入的,那么将会产生灾难。


什么函数是线程安全的?

在多线程程序中,某个函数可能会被多个线程并发的调用。

可以使用互斥锁来保证函数的线程安全性。


可重入与线程安全的关系?

个人理解,可重入的要求要比线程安全高。或者说可重入是线程安全的一个子集。


怎么编写可重入函数?

1. 不操作全局变量或static变量

2. 必须访问全局变量时,使用锁来保护

3. 不要调用不可重入函数


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值