< Previous by Date Date Index Next by Date >
< Previous in Thread Thread Index Next in Thread >

Re: [reSIProcate] unsafe static Mutex object initialization



On 21/07/11 21:03, Aron Rosenberg wrote:
> The best way to handle this is actually to make the mutex be a static
> pointer which gets allocated during a class constructor. See ThreadIf class
> and mTlsDestructorsMutex and friends for the best way to implement this.

Thanks for the fast reply about that - I've copied that code just below

I notice that:

a) this code is only for Windows - any reason it is not used on UNIX too?

b) should this be boilerplated into each of those classes I identified,
or maybe generalised in some way?

c) C++ should guarantee that the object _staticTlsInit will be
initialised before main() is called (i.e. unlikely that other threads
are running, unless some other object initialised in this way starts a
thread)

d) however, other classes may want to perform initialization before
main() is called too, and they may want to use Mutexes because they
don't really know for sure that they are being instantiated early or in
a multi-threaded scenario

e) therefore, while there is not a risk of a race-condition (as only one
thread is running), there is still a risk of using an object that is not
initialized?

If I understand it correctly, the only way to guarantee initialization
is to use a POD style mutex (for POD types, C++ should guarantee that
the state of the variable is valid before the first instruction is ever
executed)



class ThreadIf
{

.
.
.

#ifdef WIN32
/// Class to initialize TLS destructors array under Windows on program
startup.
class TlsDestructorInitializer {
public:
   TlsDestructorInitializer();
   ~TlsDestructorInitializer();
protected:
   static unsigned int mInstanceCounter;
};
static TlsDestructorInitializer _staticTlsInit;
#endif

}