If I understand correctly, in C#, a lock
block guarantees exclusive access to a set of instructions, but it also guarantees that any reads from memory reflect the latest version of that memory in any CPU cache. We think of lock
blocks as protecting the variables read and modified within the block, which means:
- Assuming you've properly implemented locking where necessary, those variables can only be read and written to by one thread at a time, and
- Reads within the
lock
block see the latest versions of a variable and writes within thelock
block become visible to all threads.
(Right?)
This second point is what interests me. Is there some magic by which only variables read and written in code protected by the lock
block are guaranteed fresh, or do the memory barriers employed in the implementation of lock
guarantee that all memory is now equally fresh for all threads? Pardon my mental fuzziness here about how caches work, but I've read that caches hold several multi-byte "lines" of data. I think what I'm asking is, does a memory barrier force synchronization of all "dirty" cache lines or just some, and if just some, what determines which lines get synchronized?