为什么inet_ntoa被设计成不可重入函数?
浏览GNU C Library的源代码,我发现inet_ntoa是用它实现的。
static __thread char buffer[18]
我的问题是,既然需要使用可重入的inet_ntoa,为什么GNU C Library的作者不使用malloc来实现呢?
谢谢。
Glancing at the source code of GNU C Library,I found the inet_ntoa is implementated with
static __thread char buffer[18]
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?
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它不使用堆的原因是为了符合标准(POSIX)和其他系统。该接口不应该让您释放返回的缓冲区。它假设静态存储。
但是通过将其声明为线程本地(使用 __thread),两个线程如果碰巧都在调用该函数,则不会相互冲突。这是 glibc 针对接口损坏的解决方法。
确实,这不是可重入,也不符合该术语的精神。如果您有一个调用它的递归函数,则不能依赖调用之间的缓冲区相同。但它可以被多个线程使用,这通常就足够了。
编辑:顺便说一下,我刚刚想起来,这个函数有一个更新版本,它使用调用者提供的缓冲区。请参阅
inet_ntop()
。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..
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.
EDIT: By the way, I just remembered, there is a newer version of this function that uses a caller-provided buffer. See
inet_ntop()
.