加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – `asprintf`线程安全吗?

发布时间:2020-12-16 04:58:41 所属栏目:百科 来源:网络整理
导读:GNU函数asprintf(打印到分配的字符串)线程安全吗? (IIC,基本上,这归结为malloc是否是线程安全的问题.) 考虑示例代码: #define _GNU_SOURCE#include stdio.h#include "getValue.h"char * getValue(int key) { char * value; asprintf(value,"%d",key); // T
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在并发线程中被调用怎么办?没有坏事会发生,他们会吗?

解决方法

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

asprintf

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”多线程安全,因为在某些情况下,它们结果并非如此,因此程序员需要处理这些问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读