QVector 项目是否共享相同的缓存行?

Do QVector items share the same cache-line?

假设我有一个 QVector 存储这些元素: {3, 4, 1, 5, 6}。所以如果我从不同的线程读取每个元素,这会导致错误共享吗? ('read' 我的意思是:int i = vector[0]; //no change involved

与 'read' 的概念相同,当 'reading' 来自不同线程时,向量的单个元素是否被视为共享资源?

是的,每个缓存行将有多个元素可用,因为 QVector 将其元素连续存储在内存中(与 std::vector 一样)。

因此可能会发生错误共享,但在现代处理器上,如果缓存行被修改,它只会导致性能下降 - 这在您的示例中不存在。

Is a single element of the vector considered a shared-resource when 'reading' it from different threads?

这取决于你所说的 'shared-resource' 是什么意思。如果您指的是标记为共享的缓存行,那么是的,但这只是因为缓存行 包含 元素,元素本身没有什么特别之处。

如果您实际上指的是 Qt 的隐式共享机制(QVector 使用),那么没有一个元素不被视为共享资源,因为引用计数发生在容器级别。

QVector 和 Qt 的所有源代码可供检查。

http://code.qt.io/cgit/qt/qtbase.git/tree/src/corelib/tools/qvector.h

http://code.qt.io/cgit/qt/qtbase.git/tree/src/corelib/tools/qvector.cpp

http://code.qt.io/cgit/qt/qtbase.git/tree/src/corelib/tools/qvector_msvc.cpp

官方文档说:

http://doc.qt.io/qt-5/qvector.html#details

QVector<T> is one of Qt's generic container classes. It stores its items in adjacent memory locations and provides fast index-based access.

里面有很多关于使用 [] 运算符 v. 使用 at(int index) v. 使用 data() 访问数组元素的描述。

Qt 线程安全在这里写得很清楚:

http://doc.qt.io/qt-5/threads-reentrancy.html

http://doc.qt.io/qt-5/thread-basics.html

http://doc.qt.io/qt-5/threads-synchronizing.html

还有其他人。