Home >Backend Development >C++ >Is Meyers' Singleton Implementation Thread-Safe in C 11 and C 03?

Is Meyers' Singleton Implementation Thread-Safe in C 11 and C 03?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-28 10:33:11201browse

Is Meyers' Singleton Implementation Thread-Safe in C  11 and C  03?

Thread Safety of Meyers' Singleton Implementation

In the provided Meyers' Singleton implementation with lazy initialization, the code is thread-safe in C 11. According to the C 11 standard (§6.7 [stmt.dcl] p4), if multiple threads attempt to access the Singleton during initialization, the other threads will wait until the initialization is complete.

GCC and Visual Studio both support this thread-safety feature (Dynamic Initialization and Destruction with Concurrency), though with different implementation dates:

  • Visual Studio: Supported since Visual Studio 2015
  • GCC: Supported since GCC 4.3

In contrast, this code is not thread-safe in C 03. Meyers' article "C and the Perils of Double-Checked Locking" analyzes various thread-safe implementations of the Singleton pattern. Ultimately, Meyers concludes that (in C 03) using a full lock around the instantiation method is the most straightforward approach to ensure concurrency across different platforms. On the other hand, double-checked locking pattern variants may introduce race conditions on certain architectures unless memory barriers are strategically placed between instructions.

The above is the detailed content of Is Meyers' Singleton Implementation Thread-Safe in C 11 and C 03?. 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