gpt4 book ai didi

c - 为什么 OSX 记录 atoi/atof 不是线程安全的?

转载 作者:太空狗 更新时间:2023-10-29 16:34:22 26 4
gpt4 key购买 nike

我知道 strtol 和 strtof 比 atoi/atof 更受欢迎,因为前者检测错误,而且在涉及非 base-10 时,strtol 比 atoi 灵活得多。

但我仍然对某些事情感到好奇:OS X 上的“man atoi”(或 atof)(尽管在 Linux 上不是!)提到 atoi/atof 不是线程安全的。坦率地说,我很难想象 atoi 或 atof 可能不是线程安全的实现。有人知道手册页为什么这样说吗?这些功能在 OS X 或任何其他平台上实际上是不安全的吗?如果它们是,那么到底为什么图书馆不根据 strtol 定义 atoi,因此是安全的?

最佳答案

查看 MacOS X 10.6.6 的手册页,它记录了两个函数,atof()atof_l() ,我怀疑这暗示了为什么该函数被认为不是线程安全的:

SYNOPSIS

#include <stdlib.h>
double atof(const char *str);

#include <xlocale.h>
double atof_l(const char *str, locale_t loc);

DESCRIPTION

The atof() function converts the initial portion of the string pointed to by str to double representation.

It is equivalent to:

      strtod(str, (char **)NULL);

The decimal point character is defined in the program's locale (category LC_NUMERIC).

While the atof() function uses the current locale, the atof_l() function may be passed a locale directly. See xlocale(3) for more information.

IMPLEMENTATION NOTES

The atof() function is not thread-safe and also not async-cancel-safe.

The atof() function has been deprecated by strtod() and should not be used in new code.

ERRORS

The function atof() need not affect the value of errno on an error.

我怀疑如果在 atof() 时当前语言环境被另一个线程更改函数正在执行,结果无法保证。否则,似乎没有理由发出警告。


我四处寻找 Darwin C 库源代码的确切位置,但没有找到。如果您转到 atoi() 的 FreeBSD 源代码, 很明显函数实现是微不足道的:

int
atoi(str)
const char *str;
{
return (int)strtol(str, (char **)NULL, 10);
}

(是的,甚至不使用原型(prototype)定义!)

strtol() 的手册页没有关于线程安全或异步取消安全的狡猾措辞。但是,快速查看 strtol() 的源代码显示它使用 isspace() ,受语言环境影响:

ISO/IEC 9899:1999,第 7.11.1.1 节 setlocale 函数

187 The only functions in 7.4 whose behavior is not affected by the current locale are isdigit and isxdigit.

(其中 §7.4 用于 <ctype.h> 。)

现在,虽然我不确定这段代码是否与 Darwin (MacOS X) 中的相同,但很可能是相似的。我认为手册页中可能有勘误的空间 - 需要更正的页面是否是 atoi() 的页面不是很清楚或 strtol() 的那个.

关于c - 为什么 OSX 记录 atoi/atof 不是线程安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4631310/

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