Home > Backend Development > C++ > body text

How to Implement a Multithreaded Singleton in C 11 Without Mutexes?

Patricia Arquette
Release: 2024-11-03 13:42:30
Original
675 people have browsed it

How to Implement a Multithreaded Singleton in C  11 Without Mutexes?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template