Home  >  Article  >  Backend Development  >  Can You Create a Thread-Safe Singleton in C 11 Without Using ``?

Can You Create a Thread-Safe Singleton in C 11 Without Using ``?

DDD
DDDOriginal
2024-10-30 02:34:29206browse

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

  1. The clear() function mentioned in the original code is used for testing and should not be included in a real-world singleton implementation.
  2. The atomic library is not referenced in the response provided by the expert.
  3. The code example included in the question is not analyzed in the response.

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!

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