gpt4 book ai didi

c - 线程安全与可重入

转载 作者:太空狗 更新时间:2023-10-29 16:15:30 25 4
gpt4 key购买 nike

最近,我问了一个问题,标题是"Is malloc thread safe?" ,在里面我问,“malloc 是可重入的吗?”

我的印象是所有可重入都是线程安全的。

这个假设是错误的吗?

最佳答案

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com