From fbeccb3954e6f45851b2ae6dd888932b3ffff8bc Mon Sep 17 00:00:00 2001 From: Vadim Zeitlin Date: Wed, 11 May 2022 00:15:46 +0200 Subject: [PATCH] Use wxAtomicInt for the global initialization counter This is slightly more efficient and simpler than using a separate critical section and can easily be done now that wxAtomicInc() returns the new value. No real changes. --- src/common/init.cpp | 34 +++++++++------------------------- 1 file changed, 9 insertions(+), 25 deletions(-) diff --git a/src/common/init.cpp b/src/common/init.cpp index 6b5956956a..e6d33d088d 100644 --- a/src/common/init.cpp +++ b/src/common/init.cpp @@ -28,7 +28,7 @@ #endif #include "wx/init.h" -#include "wx/thread.h" +#include "wx/atomic.h" #include "wx/scopedptr.h" #include "wx/except.h" @@ -130,22 +130,20 @@ static inline void Use(void *) { } static struct InitData { InitData() + : nInitCount(0) { - nInitCount = 0; - #if wxUSE_UNICODE argc = argcOrig = 0; // argv = argvOrig = NULL; -- not even really needed #endif // wxUSE_UNICODE } - // critical section protecting the counter and allowing to call - // wxInitialize() concurrently from different threads - wxCRIT_SECT_DECLARE_MEMBER(csInit); - // number of times wxInitialize() was called minus the number of times // wxUninitialize() was - size_t nInitCount; + // + // it is atomic to allow more than one thread to call wxInitialize() but + // only one of them to actually initialize the library + wxAtomicInt nInitCount; #if wxUSE_UNICODE int argc; @@ -531,17 +529,11 @@ bool wxInitialize() bool wxInitialize(int& argc, wxChar **argv) { - { - wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit); - - if ( gs_initData.nInitCount++ ) + if ( wxAtomicInc(gs_initData.nInitCount) != 1 ) { // already initialized return true; } - } // Do not keep the critical section locked, this could potentially result - // in deadlocks and is unnecessary anyhow as wxEntryStart() will be - // called exactly once and so doesn't need to be protected. return wxEntryStart(argc, argv); } @@ -549,15 +541,11 @@ bool wxInitialize(int& argc, wxChar **argv) #if wxUSE_UNICODE bool wxInitialize(int& argc, char **argv) { - { - wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit); - - if ( gs_initData.nInitCount++ ) + if ( wxAtomicInc(gs_initData.nInitCount) != 1 ) { // already initialized return true; } - } // See the comment in the overload above. return wxEntryStart(argc, argv); } @@ -565,12 +553,8 @@ bool wxInitialize(int& argc, char **argv) void wxUninitialize() { - { - wxCRIT_SECT_LOCKER(lockInit, gs_initData.csInit); - - if ( --gs_initData.nInitCount != 0 ) + if ( wxAtomicDec(gs_initData.nInitCount) != 0 ) return; - } // Don't keep the critical section locked during cleanup call neither. wxEntryCleanup(); }