In C++11, I am doing an initialization of an object and then once done, I set a flag and call a completion handler(the whole initialization is done in async manner).
Below is a simplified version:
void Foo::initializeAsync(completion_handler h){
initialize();
m_inited = true;
h();
}
Now the handler h
, would spread work to multiple threads which call methods on same Foo
object and each method has following:
void Foo:do_some_work() { // called from multiple thread
CUSTOM_ASSERT(m_inited);
//... do rest of work
}
I am wondering, how can i prevent the assert from failing in a multi-core setup(x86-64 and aarch64)?
Would a simple memory fence in initialization like below would make sure the cache lines are updated across all cores before they access it?
void Foo::initializeAsync(completion_handler h){
initialize();
m_inited = true;
std::atomic_thread_fence(std::memory_order_seq_cst); // fence
h();
}
Note: I do not want to use an atomic_bool
for m_inited as I do not want the cost of it given its updated only once in the lifetime of program.
Or is that understanding wrong as once it has been updated, the cost of lookup would be similar to not atomic bool?