Home  >  Article  >  Backend Development  >  How to Implement a Lock-Free Singleton in C 11 Without Mutexes?

How to Implement a Lock-Free Singleton in C 11 Without Mutexes?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-29 12:12:29378browse

How to Implement a Lock-Free Singleton in C  11 Without Mutexes?

Implementing Multithread-Safe Singleton in C 11 Without Mutexes

In C 11, multithreading introduces new concerns for implementing singleton classes. While the use of mutexes can guarantee thread safety, it may affect performance. This article explores an alternative approach to creating a lock-free singleton without resorting to mutexes.

Problem Statement:

How can we implement a lazy initialized singleton in C 11 without using mutexes for performance reasons?

Proposed Solution:

atomic_compare_exchange_strong:

To achieve lock-free initialization, we can leverage the std::atomic_compare_exchange_strong function. This atomic operation compares the expected value of an std::atomic variable (flag) with its desired value (desr) and, if they match, updates the variable to desr.

Initialization Process:

Within the initialize function, we perform the following steps:

  1. Set flag to 1 to indicate that initialization is in progress.
  2. Use atomic_compare_exchange_strong to check if flag is 1. If it is, we proceed with initialization.
  3. If the CAS succeeds, flag is set to 2 to indicate successful initialization.
  4. If the CAS fails, another thread has already initialized the singleton.

Thread Safety:

The concurrent execution of threads is handled by the following measures:

  • If flag is already 2, the initialization has already been completed.
  • If flag is 0, we attempt to initialize it using atomic_compare_exchange_strong.
  • If flag is 1, another thread is currently initializing, so the current thread waits.

Example Implementation:

<code class="cpp">class Singleton
{
public:
    static Singleton& get()
    {
        static Singleton instance;
        return instance;
    }

    static bool initialize(const string& name);
};</code>

Conclusion:

By harnessing the atomic_compare_exchange_strong function, we can implement a multithread-safe singleton in C 11 without relying on mutexes. This approach ensures that only one thread will successfully initialize the singleton at any given time.

The above is the detailed content of How to Implement a Lock-Free Singleton in C 11 Without Mutexes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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