Helgrind和atomic_flag

时间:2018-09-25 00:19:18

标签: c++ valgrind atomic spinlock

我尝试了在cplusplus.com使用atomic_flag的基本示例。 Valgrind的Helgrind工具报告

164 errors from 28 contexts (suppressed: 0 from 0)

带有示例,例如

==4868== Possible data race during read of size 1 at 0x605220 by thread #3
==4868== Locks held: none
==4868==    at 0x401172: test_and_set (atomic_base.h:176)
==4868==    by 0x401172: append_number(int) (helgrind_spinlock.cpp:12)
[output deleted]
==4868== This conflicts with a previous write of size 1 by thread #2
==4868== Locks held: none
==4868==    at 0x4011C9: clear (atomic_base.h:193)
==4868==    by 0x4011C9: append_number(int) (helgrind_spinlock.cpp:14)
[output deleted]

正确使用atomic_flag作为自旋锁时引用是否错误,还是Helgrind在此处给出误报?

1 个答案:

答案 0 :(得分:3)

这些是假阳性。 Helgrind不了解“低级”同步, 它只了解posix同步原语。

请参阅用户手册http://www.valgrind.org/docs/manual/hg-manual.html#hg-manual.effective-use,例如说:

  

确保您的应用程序及其使用的所有库均使用   POSIX线程原语。 Helgrind需要能够看到所有   与线程创建,退出,锁定和其他有关的事件   同步事件。为此,它拦截了许多POSIX pthreads   功能。

     

请勿从以下位置滚动您自己的线程基元(互斥量等)   Linux futex系统调用,原子计数器等的组合。这些   将Helgrind的内部正在进行的模型抛弃   会给出虚假结果。

因此,等待Helgrind了解例如c ++原子标志,您将拥有 用客户请求注释代码,让helgrind“看到” 基于原子标记的同步基元。