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

Is Meyers' Singleton Implementation Thread-Safe in Different C Standards?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-29 20:12:11963browse

Is Meyers' Singleton Implementation Thread-Safe in Different C   Standards?

Meyers' Singleton Implementation: Thread Safety in Different C Standards

Meyers' implementation of the Singleton pattern with lazy initialization poses questions about its thread safety. This article examines its behavior in different C standards.

C 11 and Later

In C 11 and subsequent standards, Meyers' Singleton implementation is thread-safe. According to the standard (§6.7 [stmt.dcl] p4), concurrent execution of the declaration must wait for initialization completion.

C 03

In C 03, Meyers' Singleton implementation was not thread-safe. Meyers' article on "Double-Checked Locking" highlights this issue. He suggests full locking around the instantiating method as a simple approach to ensure thread safety on all platforms. Double-checked locking patterns may be prone to race conditions on certain architectures without strategic memory barriers.

Supported Compilers

Dynamic Initialization and Destruction with Concurrency (Magic Statics on MSDN) is the underlying feature that ensures thread safety in C 11. The following compilers support this feature:

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

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