![](/img/trans.png)
[英]How to use an old single-threaded C++ library in a multithreaded environment
[英]What is the significance of having a function reentrant in a single-threaded environment?
在单线程环境中拥有 function 可重入的意义何在?
我了解到,要使 function 可重入,它需要能够被中断、由另一个线程进入并恢复,而不会产生任何未定义或不希望的副作用。
我读了这个问题Threadsafe vs re-entrant 。 但目前尚不清楚这如何在代码中实际发生:
如果您使用回调或递归函数,您可能会在单线程程序中遇到重入问题。
假设我们把多线程放在一边。 这个function可以说是不可重入的:
void bar() {
static bool inside_function;
inside_function = true;
assert (inside_function == true)
inside_function = false;
}
如果没有递归和回调,这不是问题。 尽管一旦添加递归,function 的不可重入性很重要:
void foo(bool repeat = true) {
static bool inside_function;
inside_function = true;
if (repeat) foo(false);
// do some stuff
// assert( inside_function == true )
std::cout << inside_function << "\n";
inside_function = false;
}
假设do some stuff
取决于inside_function == true
,那么这个递归失败(输出为1 0
)。 请注意,这是一个人为的示例,用于说明,并且使用回调问题并不总是那么明显:
struct Foo {
bool inside = false;
void operator()(Foo& f,bool call = true) {
inside = true;
if(call) f(*this,false);
std::cout << "inside operator() : " << inside << "\n";
if (inside == false) std::cout << "something went wrong !!!\n";
inside = false;
}
};
int main() {
Foo f;
f(f);
}
Output:
inside operator() : 1
inside operator() : 0
something went wrong !!!
在单线程环境中,线程安全不是问题,但重入是使用递归或回调的时候。
中断。 它们与正常执行异步并在中断处理程序中和该处理程序之外调用 function 会导致重新输入 function。 在用户空间程序的操作系统中,您不直接处理中断,而是处理由操作系统触发的信号。
在 C++20 中,在协程中调用函数可能会导致类似的重入。
最后,递归是另一种形式的重入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.