如何在C#中清除/刷新cpu缓存? [英] How can I clear/flush cpu cache in C#?

查看:220
本文介绍了如何在C#中清除/刷新cpu缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个奇怪的问题,当我将非null变量传递给另一个线程时,我将其读取为null.我可以使其变得易失,使用锁或线程屏障,但有时将其读取为null.
如果在读取此类变量之前我将3mb的数据写入数组,那么它会正常读取.因此,我确定这是一个缓存问题,但是我不知道如何直接刷新缓存.

Hi, I am having a bizarre problem where I am reading a non-null variable as null when I pass it to another thread. I can make it volatile, use locks or thread barriers, but sometime it is read as null.
If before reading such variable I write 3mb of data into an array, then it reads fine. So I am sure it is a cache problem, but I do not know how to flush the cache directly.

推荐答案

在C#代码中无法做到这一点.您必须在Intel汇编器中或C的ASM块中编写一小段代码,编译为.DLL,然后从C#代码中调用它.

有关说明的更多信息,请访问此处 [
There is no way to do this in C# code. You''d have to write up a small block of code either in Intel Assembler or inside an ASM block in C, compiling to a .DLL, then call that from your C# code.

More on the instructions can be found at here[^].


更新的答案;

对不起,我误会了你的问题.恐怕要刷新cpu缓存,在c#中您无能为力.但是
通过在基准测试的代码迭代之间执行一些非常大的内存操作来限制缓存.也许执行了大量代码
Updated answer;

Sorry, I misunderstand your question. For flushing the cpu cache, I am afraid there is nothing to you can do in c#. But
* Thrash the cache by doing some very large memory operations between iterations of the code you''re benchmarking. Maybe execution of huge line of codes


我遇到了类似的问题,线程池上的匿名委托正在使用私有字段的旧实例运行.诊断非常令人沮丧.

就我而言,因为这是一个NUnit测试,所以我决定在[TearDown]方法中保留对该字段的弱引用,然后等待它被垃圾回收.我认为强制GC以某种方式确保所有内核读取字段的正确值.因为如果内核在完整的GC之后读取GCed值,这对于运行时将非常不利.

显然,这种方法不适用于生产代码或高性能代码.如果我在生产代码中遇到相同的问题,我将为每个线程创建一个新对象.我将确保启动线程的委托和字段位于同一个对象中,从而确保核心HAS每次都从系统RAM中提取新对象.

您是否有机会在VMware Fusion下运行?我想知道我的问题是否是VM中错误的症状,而不是需要修复的实际问题.
I had a similar problem where anonymous delegates on the threadpool were running with old instances of a private field. It was quite frustrating to diagnose.

In my case, because it was an NUnit test, I decided to hold a weak reference to the field in the [TearDown] method and just wait for it to be garbage collected. I think forcing a GC somehow makes sure that all cores read the correct value for a field; because it would be very bad for the runtime if a core read a GCed value after a full GC.

Obviously, this approach won''t work in production code or high performance code. If I had the same problem in production code, what I would do is create a new object for each thread. I''d ensure that the delegate starting the thread and the field were in the same object, thus ensuring that the core HAS to pull the new object from system RAM each time.

Are you running under VMware Fusion by any chance? I''m wondering if my problem is a symptom of a bug in the VM, as opposed to a real-world problem that needs to be fixed.


这篇关于如何在C#中清除/刷新cpu缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆