`asprintf` 是线程安全的吗?
Is `asprintf` thread-safe?
GNU 函数asprintf
(打印到分配的字符串)线程安全吗?
(IIC,基本上,这归结为malloc
是否线程安全的问题。)
考虑示例代码:
#define _GNU_SOURCE
#include <stdio.h>
#include "getValue.h"
char * getValue(int key) {
char * value;
asprintf(&value, "%d", key); // TODO: No error handling!
// If memory allocation wasn't possible, or some other error occurs, these functions will
// return -1, and the contents of strp is undefined.
return value;
}
在这里,我不涉及任何全局变量。如果我的 getValue
在并发线程中被调用怎么办?不会有坏事发生吧?
glibc is free software 并且可能是唯一(或最重要的)实现 asprintf
.
的库
所以你可以学习(甚至contribute to improve) its source code. See its stdio-common/asprintf.c & libio/vasprintf.c源文件。
看起来确实是这样,它正在以线程安全的方式调用 malloc
和相关的东西。
是的,它是线程安全的,除非它读取语言环境。
Function: int asprintf (char **ptr, const char *template, …)
Preliminary: | MT-Safe locale | AS-Unsafe heap | AC-Unsafe mem
关于 'locale' exception,特别是:
Functions annotated with locale as an MT-Safety issue read from the locale object without any form of synchronization. Functions annotated with locale called concurrently with locale changes may behave in ways that do not correspond to any of the locales active during their execution, but an unpredictable mix thereof.
这些类型的函数被称为 "conditionally" 多线程安全,因为在某些情况下,它们并非如此,因此程序员需要注意这一点。
GNU 函数asprintf
(打印到分配的字符串)线程安全吗?
(IIC,基本上,这归结为malloc
是否线程安全的问题。)
考虑示例代码:
#define _GNU_SOURCE
#include <stdio.h>
#include "getValue.h"
char * getValue(int key) {
char * value;
asprintf(&value, "%d", key); // TODO: No error handling!
// If memory allocation wasn't possible, or some other error occurs, these functions will
// return -1, and the contents of strp is undefined.
return value;
}
在这里,我不涉及任何全局变量。如果我的 getValue
在并发线程中被调用怎么办?不会有坏事发生吧?
glibc is free software 并且可能是唯一(或最重要的)实现 asprintf
.
所以你可以学习(甚至contribute to improve) its source code. See its stdio-common/asprintf.c & libio/vasprintf.c源文件。
看起来确实是这样,它正在以线程安全的方式调用 malloc
和相关的东西。
是的,它是线程安全的,除非它读取语言环境。
Function: int asprintf (char **ptr, const char *template, …)
Preliminary: | MT-Safe locale | AS-Unsafe heap | AC-Unsafe mem
关于 'locale' exception,特别是:
Functions annotated with locale as an MT-Safety issue read from the locale object without any form of synchronization. Functions annotated with locale called concurrently with locale changes may behave in ways that do not correspond to any of the locales active during their execution, but an unpredictable mix thereof.
这些类型的函数被称为 "conditionally" 多线程安全,因为在某些情况下,它们并非如此,因此程序员需要注意这一点。