met*_*fox 5 c++ mutex c++11 false-sharing c++17
Consider:
class Vector
{
double x, y, z;
// …
};
class Object
{
Vector Vec1, Vec2;
std::mutex Mtx1, Mtx2;
void ModifyVec1() { std::lock_guard Lock(Mtx1); /* … */ }
void ModifyVec2() { std::lock_guard Lock(Mtx2); /* … */ }
};
Run Code Online (Sandbox Code Playgroud)
If either the mutexes or the guarded variables are stored contiguously and they share a cache line when cached, can this cause a sort of “cross-locking”?
If so, is it a good practice to declare the mutexes right after (or before) the variable they guard?
将类与std::hardware_destructive_interference_size( P0154 )对齐可能会避免这种影响。对象的过度对齐是否值得潜在的好处?
您的变量在您的问题中似乎无关,所以而不是hardware_destructive_interference_size您可能想要的hardware_constructive_interference_size:
struct keep_together {
std::mutex m;
Vector v;
};
alignas(std::hardware_constructive_interference_size) keep_together k1;
alignas(std::hardware_constructive_interference_size) keep_together k2;
Run Code Online (Sandbox Code Playgroud)
destructive您想要用于无锁队列等情况,线程正在读取两个不同的atomics 并且您想要确保它们都实际被加载。如果这是一个问题,您需要解释为什么您要避免错误共享。
在它所保护的变量之后(或之前)声明互斥锁以增加它们位于同一缓存行的机会是一个好习惯吗?
这就是constructive干扰。