localtime_r 应该是线程安全的,但在 Valgrind DRD 中导致错误
我尽可能多地搜索谷歌,但找不到任何好的答案。
localtime_r 应该是一个用于获取系统时间的线程安全函数。然而,当使用 Valgrind --tool=drd 检查我的应用程序时,它始终告诉我该函数存在数据竞争条件。常见的搜索结果是否在欺骗我,或者我只是错过了一些东西?用互斥体包围每个 localtime_r 调用似乎效率不高,特别是如果它首先应该是线程安全的。这是我使用它的方式:
timeval handlerTime;
gettimeofday(&handlerTime,NULL);
tm handlerTm;
localtime_r(&handlerTime.tv_sec,&handlerTm);
有什么想法吗?
I searched google as much as I could but I couldn't find any good answers to this.
localtime_r is supposed to be a thread-safe function for getting the system time. However, when checking my application with Valgrind --tool=drd, it consistantly tells me that there is a data race condition on this function. Are the common search results lying to me, or am I just missing something? It doesn't seem efficient to surround each localtime_r call with a mutex, especially if it is supposed to by thread safe in the first place. here is how i'm using it:
timeval handlerTime;
gettimeofday(&handlerTime,NULL);
tm handlerTm;
localtime_r(&handlerTime.tv_sec,&handlerTm);
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果文档说它是可重入 (因此线程安全),那么它就是。
如果代码(不是您的代码)中存在错误并且该函数并不是真正线程安全的,那么您对此无能为力(除非使用另一个函数),而且它是您不能在代码中修复这个问题:函数必须按照记录的方式运行。
但是,我会谨慎对待 valgrind 给出的结果。这是一个很棒的工具,我经常使用它。但有时,这只是错误。对于像检测竞争条件这样困难的事情,我会更加小心它所说的内容。尤其是关于已经使用了几十年的标准函数。
我的建议是:忽略它。如果您遇到问题并认为
localtime_r()
是造成该问题的原因,请写信至相应的邮件列表来报告该问题,和/或使用其他函数。与此同时,你应该一切都好。
If the documentation says it is reentrant (and thus thread-safe), then it is.
If ever there was a bug in the code (not your code) and the function wasn't really thread-safe, there is nothing much you can do about it (unless using another function), and it's not up to you to fix this in your code: the function must behave the way it is documented.
However, I would be careful with the results given by
valgrind
. It is a great tool, and I use it often. But sometimes, it is just wrong. And for something as hard as detecting race conditions, I would be even more careful about what it says. Especially about a standard function that is beeing used for decades.My advice here would be: just ignore it. If you ever experience issues and believe
localtime_r()
is responsible for it, write to the appropriate mailing-list to report the issue, and/or use another function.In the meanwhile, you should be just fine.
从联机帮助页:
只要您没有直接在代码中访问任何这些变量,valgrind 就可能报告误报。它是否为您提供了有关函数中竞争条件存在位置的更多详细信息?
除非您与 valgrind 有进一步的证实,否则我认为继续使用它而不需要额外的锁是安全的。
From the manpage:
As long as you aren't accessing any of those variable directly in your code, it seems possible that valgrind is reporting a false positive. Does it give you any further detail about where it thinks the race condition exists within the function?
Unless you have further corroboration with valgrind, I would think it's safe to continue using it without extra locks.