While back, I found something like following code from production and quite a bit surprised. IsReady
or IsDirty
function is very frequently called from main thread which enters a lock to check a shared boolean value. Yes, it was before C++11 and we didn’t have common framework for async task scheduling. Quick fix was just removing lock for m_isReady
and added volatile
specifier. However, volatile
is not really synchronization primitive. Moreover, Visual Studio had different behavior in different versions back then.
// IsDirty called from main thread frequently.
bool Foo::IsDirty()
{
ScopedLock(m_aLock);
return m_isReady;
}
// Process run worker thread.
void Foo::Process()
{
ScopedLock(m_aLock);
// Do expensive work here.
// Write result to shared variable.
m_isReady = true;
}