False sharing of protected member variables?

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); /* … */ }
};

If either mutexes or protected variables are stored adjacent to each other and they share the cache line during caching, can this be a kind of "cross-lock"?

If so, is it good to declare mutexes immediately after (or before) the variable they guard?

Aligning a class with std::hardware_destructive_interference_size( P0154 ) can avoid this effect. Are there potential benefits to revaluing the property?

+4
source share
1 answer

Your variables seem to be unrelated in your question, so instead, hardware_destructive_interference_sizeyou probably want 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;

destructive, , , , atomic, , . , , - , .

( ) , , , ?

constructive.

+3

Source: https://habr.com/ru/post/1654800/


All Articles