std::locale 导致 Helgrind 出错

std::locale causing errors with Helgrind

在使用 Helgrind 分析我的程序时,我注意到我遇到了很多类似于以下内容的错误:

==8347== Possible data race during read of size 4 at 0x53C47A0 by thread #2
==8347== Locks held: none
==8347==    at 0x50E4E68: std::locale::locale() (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==8347==    by 0x515B1DE: std::__cxx11::basic_stringstream<char, std::char_traits<char>, std::allocator<char> >::basic_stringstream(std::_Ios_Openmode) (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)

==8347== This conflicts with a previous write of size 4 by thread #1
==8347== Locks held: 1, at address 0xFFEFFF638
==8347==    at 0x50E3115: std::locale::~locale() (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)

所以我想知道,这会成为问题吗?如果是,我可以解决它吗?我知道如何使用 Valgrind 抑制错误,但我不确定是否应该担心。

正如 std::locale 文档所说:

Internally, a locale object is implemented as-if it is a reference-counted pointer to an array (indexed by std::locale::id) of reference-counted pointers to facets: copying a locale only copies one pointer and increments several reference counts. To maintain the standard C++ library thread safety guarantees (operations on different objects are always thread-safe), both the locale reference count and each facet reference count are updated in thread-safe manner, similar to std::shared_ptr.

所以我想说你可能不必担心太多,但另一方面,如果你在线程中分配(不仅仅是读取)带有引用计数(如 shared_ptr)的指针,你最好使用锁来防止错误的重新分配。

这里有一个很好的解释:std::shared_ptr thread safety