I have two threads, thread A and thread B, and a global object stored in a unique_ptr
. Thread A initializes the object once, and thread B is designed to access the object only after the initialization is done. Here is my code:
std::unique_ptr<Object> object;
std::atomic<bool> isInitialized = false;
void createObject()
{
object = std::make_unique<Object>();
isInitialized = true;
}
Object& getObject()
{
if (!isInitialized)
assert(false);
return *object;
}
I’m still learning about the basics of the C++ memory model so is this solution correct to begin with? If so, am I correct that the atomic variable is necessary and it needs to be present in both functions even though thread A creates the object before thread B tries to access it since otherwise the modification of object
may not be visible to thread B?
bananab0y is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3