LoveCoding
LoveCoding

Reputation: 1

Are std::unique_ptr assignments and reading thread safe with respect to control block?

private std::unique_ptr<MyClass> myptr_;

LazyInit()
{
   // Assume mutex lock. Skipping specifics since it is not relevant for this question
   auto mylock = LOCK(); 
   
   if(!myptr_)
   {
       // myptr_ is only initialized once ever. Once assigned it is never deleted till end of process.
       myptr_ = make_unique<MyClass>();
   }
   
   // lock released when mylock goes out of scope.
}

Read()
{
    // No locking here.
    // Expectation: myptr_ is either null or valid value. Totally fine if myptr_ just got assigned, next call to Read will read the value.
    if(myptr_)
    {
        myptr_->DoSomething();
    }
}


Question: Is it guaranteed that when Read() executes, myptr_ will either be null or will have a valid value? (Specifically, is the assignment to myptr_ in LazyInit atomic, with respect to memory alignments?) Assume that LazyInit and Read can both be called by multiple threads.

Based on documentation below, it seems like myptr_ could have a garbage value (other than null or valid value). Could some one clarify this by confirming / denying my understanding?

Related documentation: ( https://learn.microsoft.com/en-us/cpp/standard-library/thread-safety-in-the-cpp-standard-library?view=vs-2019 ) "If an object is being written to by one thread, then all reads and writes to that object on the same or other threads must be protected. For example, given an object A, if thread 1 is writing to A, then thread 2 must be prevented from reading from or writing to A."

Upvotes: 0

Views: 756

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118302

No, it's not guaranteed. std::unique_ptr's assignment operator is not documented to be thread-safe. The bool operator overload is also not documented to be thread-safe, either.

When it comes to the C++ library, unless something is explicitly specified as thread-safe, it's not. Unless you can find documentation in a C++ class or its method that it's explicitly thread-safe, it is not.

Upvotes: 1

Related Questions