< Previous by Date | Date Index | Next by Date > |
< Previous in Thread | Thread Index | Next in Thread > |
Actually, this too can be problematic, because you can get multiple initializations of the Mutex if multiple threads try to construct the same type of object at once. And, if you have any static functions that try to use the mutex, you're sunk because it might not be initialized. A better way to do this is the following: In the header: class FoobaJooba { static Mutex& getMutex() { static Mutex mMutex; return mMutex; } // Nobody should actually touch this, or use it to try to determine // whether the mutex has been initialized; this bool could be anything // during static initialization. It exists solely to cause getMutex() // to be called sometime during static init. static bool ensureInitialized; }; In the implementation file: bool FoobaJooba::ensureInitialized=(&initMutex()!=0); This ensures that getMutex() is called sometime during static initialization (it might be called multiple times, but this is ok, since there is only one thread of execution), so multiple init problems don't crop up, and it also ensures that if somebody tries to access the mutex during static init _before_ ensureInitialized has been initialized, the mutex is just initialized a little bit early. Now, this is still not perfect; it doesn't prevent nastiness during static _de_initilization. Best regards, Byron Campen Best regards, Byron Campen 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. |