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

Is Meyers' Singleton Pattern Thread-Safe in C 11 and Later?

Patricia Arquette
Release: 2024-12-30 17:04:10
Original
898 people have browsed it

Is Meyers' Singleton Pattern Thread-Safe in C  11 and Later?

Thread Safety of Meyers' Singleton Pattern Implementation

This implementation of Meyers' Singleton pattern using lazy initialization raises questions about its thread safety.

Meyers' Singleton Implementation

The provided code for the Singleton pattern is as follows:

static Singleton& instance()
{
     static Singleton s;
     return s;
}
Copy after login

Thread Safety Analysis

In C 11, this implementation is thread safe due to the guarantee in §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."

Compilers like GCC (since version 4.3) and Visual Studio (since 2015) support this feature.

C 03 Implementation

In C 03, the code was not thread safe. Meyers' article "C and the Perils of Double-Checked Locking" discusses such concerns. Full locking around the instantiating method was recommended to guarantee concurrency, while double-checked locking variants might encounter race conditions on specific architectures without memory barriers.

The above is the detailed content of Is Meyers' Singleton Pattern Thread-Safe in C 11 and Later?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template