为什么将inet_ntoa设计为不可重入函数? [英] Why inet_ntoa is designed to be a non-reentrant function?

查看:326
本文介绍了为什么将inet_ntoa设计为不可重入函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

浏览GNU C库的源代码,我发现inet_ntoa是用

Glancing at the source code of GNU C Library,I found the inet_ntoa is implementated with

static __thread char buffer[18]

我的问题是,由于有必要使用reeentrant inet_ntoa,为什么GNU C库的作者不使用malloc来实现它?

My question is, since there is a need to use reeentrant inet_ntoa,why do not the author of GNU C Library use malloc to implementate it?

谢谢.

推荐答案

不使用堆的原因是为了符合标准(POSIX)和其他系统.该接口只是不能让您释放返回的缓冲区.它假定为静态存储..

The reason it's not using the heap is to conform with standards (POSIX) and other systems. The interface is just not such that you are supposed to free the buffer returned. It assumes static storage..

但是通过将其声明为本地线程(使用__thread),如果两个线程恰巧都在调用该函数,则它们不会相互冲突.这是glibc解决界面损坏的方法.

But by declaring it as thread local (with __thread), two threads do not conflict with each other if they happen to both be calling the function. This is glibc's workaround for the brokenness of the interface.

的确,这不是可重入,也不符合该术语的精神.如果您有一个调用它的递归函数,则不能依赖于两次调用之间的缓冲区是相同的.但是它可以被多个线程使用,这通常就足够了.

It's true that this is not re-entrant or consistent with the spirit of that term. If you have a recursive function that calls it, you cannot rely on the buffer being the same between calls. But it can be used by multiple threads, which often is good enough.

顺便说一句,我刚刚记得,此函数有一个较新的版本,它使用调用者提供的缓冲区.参见 inet_ntop() .

By the way, I just remembered, there is a newer version of this function that uses a caller-provided buffer. See inet_ntop().

这篇关于为什么将inet_ntoa设计为不可重入函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆