I have a class with code as follows
private readonly object m_lock = new object();
private IClient m_client
private object m_context;
When setting the client and context, I lock as follows
lock(m_lock)
{
m_client = theClientFromSomewhere;
m_context = contextObject;
}
My question is, if I only need to get the m_client
by itself, is it safe to do this?
var localClient = m_client;
Debug.Assert(localClient != null);
localClient.DoStuff();
m_client
is a reference type, so the read (when assigning to localClient
) is guaranteed to be atomic, so this should work fine on a single CPU.
I could (also in theory) make the m_client
variable volatile
, and then this would be safe across multiple cpu's by preventing out-of-order reads by other CPU's, but the question is, does the lock-when-writing make it safe to read without being volatile?
Does locking when writing "flush" the CPU caches so that when they do a read it won't be out-of-order?