I have the following Lock statement:
private readonly object ownerLock_ = new object();
lock (ownerLock_)
{
}
Should I use volatile keyword for my lock variable?
private readonly volatile object ownerLock_ = new object();
On MSDN I saw that it usually used for a field that is accessed without locking, so if I use Lock I don’t need to use volatile?
From MSDN:
The volatile modifier is usually used for a field that is accessed by
multiple threads without using the lock statement to serialize access.
If you’re only ever accessing the data that the lock “guards” while you own the lock, then yes – making those fields volatile is superfluous. You don’t need to make the
ownerLock_variable volatile either. (You haven’t currently shown any actual code within thelockstatement, which makes it hard to talk about in concrete terms – but I’m assuming you’d actually be reading/modifying some data within thelockstatement.)volatileshould be very rarely used in application code. If you want lock-free access to a single variable,Interlockedis almost always simpler to reason about. If you want lock-free access beyond that, I would almost always start locking. (Or try to use immutable data structures to start with.)I’d only expect to see
volatilewithin code which is trying to build higher level abstractions for threading – so within the TPL codebase, for example. It’s really a tool for experts who really understand the .NET memory model thoroughly… of whom there are very few, IMO.