Summary: | Race condition during initialization of static local variable objects | ||
---|---|---|---|
Product: | [Developer tools] kdevplatform | Reporter: | Krzysztof Nowicki <krissn> |
Component: | language | Assignee: | kdevelop-bugs-null |
Status: | RESOLVED FIXED | ||
Severity: | normal | CC: | vkrevs |
Priority: | NOR | ||
Version: | git master | ||
Target Milestone: | --- | ||
Platform: | Compiled Sources | ||
OS: | Microsoft Windows | ||
Latest Commit: | Version Fixed In: |
Description
Krzysztof Nowicki
2010-06-11 20:48:56 UTC
Adding a mutex is not an option as these functions are supposed to be as fast as possible and locking is a very slow operation. we simply need to call them once in a defined way where no threads can exist, which will initialize that sooner and should solve the issues. What about using something like conditional mutex locker class. It would essentially be a QMutexLocker(), but with an additional argument telling it to lock or not: bool globalInstanceInitialized = false; QMutex globalInstanceCreationMutex; SomeObject& globalInstance() { QCondMutexLocker(&globalInstanceCreationMutex, !globalInstanceInitialized); static SomeObject globalInstance(params); globalInstanceInitialized = true; return globalInstance; } class QCondMutexLocker { public: QCondMutexLocker(QMutex *pMutex, bool lock) : pMtx(pMutex), lck(lock) { if (lock) pMutex->lock(); } ~QCondMutexLocker() { if (lck) pMutex->unlock(); } }; When the function is called for the first time by multiple thread, all of them will (except one) will wait on the mutex, because lock == true. When the mutex is released, the instance will be already initialized. Any subsequent call will not use the mutex, because the global flag is set to true. The only additional overhead are 2 additional 'if' statements. Oops, missed the QCondMutexLocker variables: private: QMutex *pMtx; bool lck; } pthread_once() is a better solution ... (In reply to comment #5) > pthread_once() is a better solution ... As long as you have pthreads available... There is a Win32 port of pthreads for example, but the whole point of using Qt4 is to be platform independent. All I'm saying (well, the pthread_once's man page) that using a mutex in this context won't solve the problem. Since other cross-platform libraries such as RogueWave's SourcePro provide a portable abstraction for thread-safe initialization, there is no technical reason why Qt could not do something similar. Until it does you have a choice to make - live with the bug or use an #ifdef. this should be fixed since quite some time now |