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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-21 07:26:10452browse

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

Is Meyers' Singleton Design Thread-Safe?

The presented implementation of Meyers' Singleton pattern, using lazy initialization, raises the question of thread safety. Here's an analysis of why this code is thread-safe in C 11 and how it achieves thread safety.

Thread Safety in C 11

According to the C 11 standard, §6.7 [stmt.dcl] p4:

If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.

This implies that in C 11, the above implementation becomes thread-safe. The standard requires that thread execution waits for the completion of initialization before accessing the variable, ensuring thread safety.

Support in Compilers

The following compilers provide support for Dynamic Initialization and Destruction with Concurrency, which enables this feature:

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

Note for C 03

In C 03, the code was not thread-safe. Meyers in his article, "C and the Perils of Double-Checked Locking," suggests that in C 03, full locking around the instantiating method is the most straightforward way to ensure thread safety across platforms.

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