Home > Article > Backend Development > Can You Create a Thread-Safe Singleton in C 11 Without Using ``?
How to Implement a Multithread-Safe Singleton in C 11 Without Using
Introduction
Implementing thread-safe singletons in C 11 has been a topic of debate since the introduction of multithreading. While mutexes provide a straightforward way of achieving thread safety, they can introduce performance overhead. This article explores an alternative approach to implementing multithread-safe singletons without using mutexes.
Lazy Initialization with Concurrent Waiting
C 11 introduces a new language feature that simplifies the implementation of lazy initialization. Concurrent execution will now wait if a static local variable is already being initialized, eliminating the need for manual locking.
Implementation
A simple static function that retrieves the singleton instance can be implemented as follows:
<code class="cpp">static Singleton& get() { static Singleton instance; return instance; }</code>
This function will provide correct behavior in C 11 as long as the compiler properly implements the standard.
Discouragment of Singletons
Despite this simplified implementation, the author emphasizes that the use of singletons is generally discouraged. They advocate for avoiding singletons altogether due to their inherent limitations.
Additional Notes
The above is the detailed content of Can You Create a Thread-Safe Singleton in C 11 Without Using ``?. For more information, please follow other related articles on the PHP Chinese website!