В этом коде. Несмотря на то, что писатель и читатель работают в разных буферах, Threadsanitizer сообщает о гонке данных на полях данных A, B и т. Д.#include
#include
#include
#include
#include
// Struct holding data
struct MyClass {
double a;
double b;
double c;
double d;
};
// Two data buffers
std::array buffers;
// Index of the currently readable buffer
std::atomic index{0};
// Writer thread
void writer_thread() {
for (int i = 0; i < 10; ++i) {
uint8_t next = 1 - index.load(std::memory_order_relaxed);
MyClass data;
data.a = 1.0 + i;
data.b = 2.0 + i;
data.c = 3.0 + i;
data.d = 4.0 + i;
buffers[next] = data;
index.store(next, std::memory_order_release);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
// Reader thread
void reader_thread() {
for (int i = 0; i < 10; ++i) {
uint8_t i_read = index.load(std::memory_order_acquire);
MyClass data = buffers[i_read];
// work with data
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
int main() {
std::thread writer(writer_thread);
std::thread reader(reader_thread);
writer.join();
reader.join();
return 0;
}
< /code>
Безопасен ли этот код под моделью памяти C ++?
Почему Threadsanitizer сообщает о гонке? Это ложный позитив?
Подробнее здесь: https://stackoverflow.com/questions/796 ... ta-sharing
TSAN и беззаконный обмен данными ⇐ C++
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение