Implementing Multithreaded Singleton in C 11
With the advent of C 11's multithreading capabilities, the traditional approach of using mutexes for singleton implementation may no longer be necessary for performance reasons.
Lock-Free Singleton with Atomic Operations
One method to create a singleton without mutexes is through atomic operations. Using atomic bool variables and the std::atomic_compare_exchange_strong() function, you can implement the following solution:
<code class="cpp">public class Singleton { private static atomic<int> flag = 0; private static string name; public static bool initialized() { return (flag == 2); } public static bool initialize(string name_) { if (flag == 2) { return false; // Already initialized } int exp = 0, desr = 1; bool willInitialize = std::atomic_compare_exchange_strong(&flag, &exp, desr); if (!willInitialize) { return false; // Another thread CASed before us } initialize_impl(name_); assert(flag == 1); flag = 2; return true; } private static void initialize_impl(string name) { name = name; } }</code>
C 11 Thread-Safe Initialization
C 11 introduced thread-safe static initialization, removing the need for manual locking. Concurrent execution waiting for static local variables to be initialized, allowing for the following simplified implementation:
<code class="cpp">static Singleton& get() { static Singleton instance; return instance; }</code>
Alternatives to Singleton
It's important to note that while these solutions provide multithreaded safe singleton implementations, the Singleton pattern itself is not always the best design choice. Consider alternatives such as passing objects as function arguments, using dependency injection, or employing the State Pattern.
The above is the detailed content of Is a Lock-Free Singleton with Atomic Operations a Better Approach in C 11 Than Using Mutexes?. For more information, please follow other related articles on the PHP Chinese website!