- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
最佳答案
TL;DR:一个函数可以是可重入的、线程安全的,或者两者兼而有之。
thread-safety 的维基百科文章和 reentrancy非常值得一读。以下是一些引用:
一个函数是线程安全的如果:
it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time.
一个函数是可重入如果:
it can be interrupted at any point during its execution and then safely called again ("re-entered") before its previous invocations complete execution.
作为可能重入的例子,维基百科给出了一个被系统中断调用的函数的例子:假设当另一个中断发生时它已经在运行。但是不要仅仅因为您没有使用系统中断进行编码就认为您是安全的:如果您使用回调或递归函数,您可能会在单线程程序中遇到重入问题。
The key for avoiding confusion is that reentrant refers to only one thread executing. It is a concept from the time when no multitasking operating systems existed.
示例
(根据维基百科文章略作修改)
例子1:非线程安全,不可重入
/* As this function uses a non-const global variable without
any precaution, it is neither reentrant nor thread-safe. */
int t;
void swap(int *x, int *y)
{
t = *x;
*x = *y;
*y = t;
}
例子2:线程安全,不可重入
/* We use a thread local variable: the function is now
thread-safe but still not reentrant (within the
same thread). */
__thread int t;
void swap(int *x, int *y)
{
t = *x;
*x = *y;
*y = t;
}
例子3:非线程安全,可重入
/* We save the global state in a local variable and we restore
it at the end of the function. The function is now reentrant
but it is not thread safe. */
int t;
void swap(int *x, int *y)
{
int s;
s = t;
t = *x;
*x = *y;
*y = t;
t = s;
}
例子4:线程安全,可重入
/* We use a local variable: the function is now
thread-safe and reentrant, we have ascended to
higher plane of existence. */
void swap(int *x, int *y)
{
int t;
t = *x;
*x = *y;
*y = t;
}
关于c - 线程安全与可重入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/856823/
我是一名优秀的程序员,十分优秀!