This repository contains a C++ solution that demonstrates the proper way of implementing lazy initialization with multithreading. Lazy initialization is a design pattern used to defer the creation of an object until it is needed. Multithreading is utilized to ensure thread safety and efficient utilization of system resources.
- C++20 compatible compiler
- This code has been tested and confirmed to work with both Mingw g++ and Windows MSVC compilers. GCC compiler should be avoided.
- Standard C++ libraries
- Git
To use this solution, follow these steps:
- Clone the repository to your local machine:
git clone https://github.com/BardiParsi/LazyInitialization.git
- Navigate to the cloned directory:
cd LazyInitialization1
- Compile the source code:
g++ -std=c++20 -pthread main.cpp -o main
- Run the executable:
./main
The solution consists of the following key components:
ExpensiveObject
: Represents an expensive object that is initialized lazily.LazyInitialization
: Manages the lazy initialization ofExpensiveObject
using a mutex and atomic flags to ensure thread safety and efficient resource utilization.main
: Demonstrates the usage ofLazyInitialization
with multiple threads.
ExpensiveObject
: Simulates an expensive object that takes some time to initialize.LazyInitialization
: Implements lazy initialization usingstd::once_flag
andstd::atomic<bool>
. TheuseObject()
function ensures that the object is initialized only once and is thread-safe.main
: Creates a vector of multiple threads that attempt to use theExpensiveObject
simultaneously, demonstrating the effectiveness of lazy initialization and multithreading.
Contributions are welcome! Feel free to submit issues or pull requests for any improvements or additional features.
This project is licensed under the GNU General Public License (GPL). Author: Bardi (Masoud) Parsi Contact: [email protected]