Implementing Multithreaded Singleton in C 11 Without Mutexes
With the introduction of multithreading capabilities in C 11, the question arises on how to implement singletons without utilizing mutexes for performance optimization. A suggested approach involves the use of atomic variables and the std::atomic_compare_exchange_strong() function:
<code class="cpp">class Singleton { public: static bool isInitialized() { return (flag == 2); } static bool initizalize(const string& name_) { if (flag == 2) return false; if (flag == 1) return false; int exp = 0; int desr = 1; bool willInitialize = std::atomic_compare_exchange_strong(&flag, &exp, desr); if (!willInitialize) { cout << "Somebody else CASed at aprox same time" << endl; return false; } else { initialize_impl(name_); assert(flag == 1); flag = 2; return true; } } static void clear() { name.clear(); flag = 0; } private: static void initialize_impl(const string& name_) { name = name_; } static atomic<int> flag; static string name; };</code>
Atomic variables and the std::atomic_compare_exchange_strong() function ensure thread safety without introducing thread synchronization overhead. However, this approach still requires careful handling to prevent data races and ensure proper initialization.
C 11 Standard Enforces Initialization Safety
Interestingly, C 11's standard eliminates the need for manual locking in certain scenarios. The following code snippet leverages this behavior:
<code class="cpp">static Singleton& get() { static Singleton instance; return instance; }</code>
Concurrent execution attempting to initialize the static variable instance will implicitly wait for its completion, reducing potential race conditions.
Singleton Anti-Pattern
While the above approaches provide solutions for multithreaded singleton implementation, it's worth noting that using singletons is generally discouraged. They can introduce coupling, state dependencies, and complicate unit testing. Alternative design patterns are often preferable for managing shared resources and dependencies.
The above is the detailed content of How to Implement a Multithreaded Singleton in C 11 Without Mutexes?. For more information, please follow other related articles on the PHP Chinese website!