`asprintf`线程安全吗?

imz*_*hev 6 c printf multithreading glibc asprintf

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;
}
Run Code Online (Sandbox Code Playgroud)

在这里,我不触及任何全局变量.如果我getValue在并发线程中调用了怎么办?没有坏事会发生,他们会吗?

edm*_*dmz 6

是的,它是线程安全的,除非它读取区域设置.

asprintf

函数:int asprintf(char**ptr,const char*template,...)
初步:| MT-Safe区域设置| AS-Unsafe堆| AC-Unsafe mem

关于'locale' 例外,特别是:

使用区域设置注释的函数作为MT-Safety问题从区域设置对象读取而不进行任何形式的同步.使用与语言环境更改同时调用的语言环境注释的函数可能以与执行期间活动的任何语言环境不对应的方式运行,但其行为不可预测.

这些类型的函数被称为"有条件"多线程安全,因为在某些情况下,它们结果并非如此,因此程序员需要处理这些问题.

  • 有些平台提供`asprintf_l`,它带有`locale_t`参数,应该完全是线程安全的. (2认同)