C++ ThreadSanitizer报告的数据竞争
我正在使用Clang-8并启用线程消毒剂来编译下面的代码C++ ThreadSanitizer报告的数据竞争,c++,multithreading,atomic,memory-barriers,thread-sanitizer,C++,Multithreading,Atomic,Memory Barriers,Thread Sanitizer,我正在使用Clang-8并启用线程消毒剂来编译下面的代码 std::atomic<std::string*> ptr {nullptr}; int data {0}; void producer() { std::string* p = new std::string("Hello"); data = 42; ptr.store(p, std::memory_order_release); } void consumer() { std::string* p2
std::atomic<std::string*> ptr {nullptr};
int data {0};
void producer() {
std::string* p = new std::string("Hello");
data = 42;
ptr.store(p, std::memory_order_release);
}
void consumer() {
std::string* p2;
if(!(p2 = ptr.load(std::memory_order_relaxed))) {
// Data is not ready, just return
return ;
}
std::atomic_thread_fence(std::memory_order_seq_cst);
assert(data == 42); // Never fired
}
int main() {
std::thread t1(producer);
std::thread t2(consumer);
t1.join(); t2.join();
}
更新
我已经阅读了,并使用Clang-8编译了代码。它不显示任何数据竞争警告。因此,我认为我的情况不同。您的示例在将42存储到数据和写入数据值之间没有同步。编译器可以在producer中自由地对这两个进行重新排序,这意味着即使在屏障和检查之后,数据的值也未定义。不要使用
new
和基本指针来表示所有者。您可以发布完整的错误消息吗?@bolov我已经在底部添加了错误消息。不过,它看起来像是误报