+ 1

Is call_once better or not for singleton

Hi Refer code below : Which class is better for singleton implementation ? Singleton (mutex and double check for nullptr ) or singletonNew (using call_once)? Also what should be default value to initialise Mutex and once_flag ? I just used both of them without initialisation https://code.sololearn.com/cDJrY9maO2Th/?ref=app

13th Apr 2022, 3:12 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
1 Answer
+ 1
Both implementations, Singleton (using mutex and double-check for nullptr) and SingletonNew (using call_once), are valid ways to implement the Singleton design pattern in C++. The choice between them depends on the specific requirements and constraints of your application. Singleton (using mutex and double-check): Pros: Simple and easy to understand implementation. Lazy initialization: The instance is created only when needed. Cons: Requires manual synchronization using a mutex, which can introduce some overhead. The double-checked locking pattern is known to be prone to subtle bugs in certain situations. SingletonNew (using call_once): Pros: Uses the call_once mechanism provided by the standard library, which guarantees thread-safe initialization. Lazy initialization: The instance is created only when needed. No need for explicit mutex usage, reducing the chance of synchronization bugs. Cons: Requires C++11 or later to use the call_once mechanism. Slightly more complex implementation due to the usage of call_once and the associated once_flag. In terms of thread safety, both implementations provide the necessary guarantees. The choice between them depends on factors like personal preference, codebase requirements, and the available C++ language version. Regarding the default values to initialize mutex and once_flag: mutex (singleton implementation): It is recommended to initialize the mutex as a static member of the class, using the default constructor. The default constructor initializes the mutex in an unlocked state. The line mutex singleton::m; in your code achieves this. once_flag (singletonNew implementation): Similarly, it is recommended to initialize the once_flag as a static member of the class. Since once_flag is a class type, it is implicitly default-initialized, which initializes it in the "uncalled" state. The line once_flag singletonNew::flag; in your code achieves this.
2nd Jun 2023, 5:44 PM
AgentSmith