lundi 5 septembre 2016

std::atomic lock free for class with composition

I have the following unit test which seems to suggest that std::atomic is lock free for a struct with std::string or a class with inheritance, but not a class with composition.

I was expecting std::string might require lock due to heap allocation etc. I was also expecting that composition and inheritance are close enough in terms of how the memory is laid out etc, that their lock-freeness will be the same.

Any suggestions why my expectation does not hold true? I am on ubuntu 14.04 and gcc 4.9.

TEST(Test, PODWithString) {
  struct POD {int a; std::string b;};
  std::atomic<POD> pod({1,"2"});
  EXPECT_TRUE(pod.is_lock_free());
}

TEST(Test, INHERITANCE) {
  struct B {B(int x): x(x) {} int x; };                                                                                        
  struct D : public B {D(int x, int a): B(x),a(a) {} int a; };                                                                 
  std::atomic<D> d(D(1,2));
  EXPECT_TRUE(d.is_lock_free());                                                                                               
}

TEST(Test, PODNested) {
  struct POD {int x; int y;};
  struct PODNested {int a; POD b;};
  std::atomic<PODNested> pod_nested({1, {2,3}});
  EXPECT_FALSE(pod_nested.is_lock_free());
}

Aucun commentaire:

Enregistrer un commentaire