views:

156

answers:

1

Given:

class Foo {
  Foo() {};
};

class Bar {
  static int counter;
  Bar() { ++counter; }
}

It's clear that Foo::Foo is thread safe whereas Bar::bar is not.

Furthermore, it's clear that if a function is written in such a way so that it's not thread-safe, then clearly putting it in a constructor makes that constructor not thread safe.

However, are there extra gotchas that I need to worry about constructors? I.e. a piece of code with mutex/locks such that if it was in a function body, it would be thread safe, but if I stuck it in a constructor, based on the complexity of C++'s constructors, weird things happen and it's no longer thread safe?

Thanks!

Edit: you can assume I'm using g++.

+1  A: 

I would avoid any static values in an object used by a thread.

Why not pass in the value needed as a parameter for the constructor?

Or actually, put a mutex around the constructor in your thread. I wouldn't let the other classes be responsible for that.

Daniel A. White