Does locking ensure reads and writes are flushed from caches? If so, how?

旧时模样 提交于 2019-12-04 06:12:33

Check the work of Eric Lippert: http://blogs.msdn.com/b/ericlippert/archive/2011/06/16/atomicity-volatility-and-immutability-are-different-part-three.aspx

Locks guarantee that memory read or modified inside the lock is observed to be consistent, locks guarantee that only one thread accesses a given hunk of memory at a time, and so on.

So yes, as long as you lock each time before accessing shared resources, you can be pretty sure its up to date

EDIT look up the following post for more information and a very usefull overview: http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/

Well, the article explains it:

  1. Reads cannot move before entering a lock.

  2. Writes cannot move after exiting a lock.

And more explanation from the same article:

When a thread exits the lock, the third rule ensures that any writes made while the lock was held are visible to all processors. Before the memory is accessed by another thread, the reading thread will enter a lock and the second rule ensures that the reads happen logically after the lock was taken.

Not all c# memory reads and writes are volatile, no. (imagine if that was the case performance-wise!)

But.

How are those updates guaranteed to be flushed from CPU caches when entering / exiting a lock

CPU caches are CPU specific, however they all have some form of memory coherence protocol. That is to say, when you access some memory from a core, if it is present in another core cache, the protocol the CPU uses will ensure that the data gets delivered to the local core.

What Petar Ivanov alludes to in his answer is however very relevant. You should check out memory consistency model if you want to understand more what his point is.

Now, how C# guarantees that the memory is up-to-date is up to the C# implementers, and Eric Lippert's blog is certainly a good place to understand the underlying issues.

I’m not sure about the state of affairs in .NET, but in Java it is clearly stated that any two threads cooperating in such a way must use the same object for locking in order to benefit from what you say in your introductory statement, not just any lock. This is a crucial distinction to make.

A lock doesn’t need to “know” what it protects; it just needs to make sure that everything that has been written by the previous locker is made available to another locker before letting it proceed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!