[英]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是免费软件 ,可能是实现asprintf
的唯一(或最重要的)库。
因此,您可以学习(甚至有助于改进)其源代码。 请参阅其stdio-common / asprintf.c和libio / vasprintf.c源文件。
看起来确实如此,它以线程安全的方式调用malloc
和相关的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.