【发布时间】:2015-04-18 05:00:19
【问题描述】:
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 在并发线程中被调用怎么办?不会有坏事发生吧?
【问题讨论】:
-
如果 malloc 不是线程安全的,用户将注定失败:stackoverflow.com/questions/855763/is-malloc-thread-safe
标签: c multithreading printf glibc asprintf