Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Thread Safe Lazy Load

I have a property which is similar to the following:

private:
Foo* myFoo_m;

public:
Foo getMyFoo() const
{
    if (myFoo_m == NULL)
    {
       myFoo_m = new Foo();
       // perform initialization

This works well in a single-threaded environment, but how do I handle this in a multi-threaded environment? Most of the info I've found deals with static singletons, but in this case, myFoo is a public instance property.

I am porting this over from C# (where I can use Lazy) and Java (where I can use double check locking), but it doesn't seem that there is a straightforward way to do this in C++. I cannot rely on any external libraries (no BOOST), and this needs to work on windows and linux. I also cannot use C++11.

Any insight would be good. I am new to C++.

like image 881
Mikeyg36 Avatar asked Dec 27 '22 15:12

Mikeyg36


1 Answers

If you have access to c++11 you can use std::mutex to lock prevent multiple threads from initializing the lazy section. (Note: std::mutex only became available on Windows with VS2012)

You can even perform a scoped aquisition of the mutex with std::lock_guard:

private:

std::mutex m_init_mutex;

public:

Foo getMyFoo() const
{
    {
       std::lock_guard<std::mutex> lock(m_init_mutex);
       if (myFoo_m == NULL)
       {
          myFoo_m = new Foo();
          // perform initialization
       }
    }

EDIT: The OPs now stated that C++11 isn't an option, but perhaps this answer will be useful in the future

like image 154
Benj Avatar answered Jan 09 '23 08:01

Benj