我什么时候应该使用 _mm_sfence _mm_lfence 和 _mm_mfence
我阅读了英特尔架构的英特尔优化指南指南".
I read the "Intel Optimization guide Guide For Intel Architecture".
然而,我仍然不知道我应该什么时候使用
However, I still have no idea about when should I use
_mm_sfence()
_mm_lfence()
_mm_mfence()
谁能解释一下在编写多线程代码时应该何时使用这些?
Could anyone explain when these should be used when writing multi-threaded code?
推荐答案
警告:我不是这方面的专家.我仍在尝试自己学习这一点.不过这两天没有人回复,看来内存栅栏指令的高手并不多.所以这是我的理解......
Caveat: I'm no expert in this. I'm still trying to learn this myself. But since no one has replied in the past two days, it seems experts on memory fence instructions are not plentiful. So here's my understanding ...
英特尔是一个弱序内存系统.这意味着你的程序可能会执行
Intel is a weakly-ordered memory system. That means your program may execute
array[idx+1] = something
idx++
但是在更改为 array 之前,对 idx 的更改可能是全局可见的(例如,对于在其他处理器上运行的线程/进程).在两个语句之间放置围栏将确保写入发送到 FSB 的顺序.
but the change to idx may be globally visible (e.g. to threads/processes running on other processors) before the change to array. Placing sfence between the two statements will ensure the order the writes are sent to the FSB.
与此同时,另一个处理器运行
Meanwhile, another processor runs
newestthing = array[idx]
可能已经缓存了 array 的内存并且有一个陈旧的副本,但是由于缓存未命中而获得更新的 idx.解决方案是预先使用围栏来确保负载同步.
may have cached the memory for array and has a stale copy, but gets the updated idx due to a cache miss. The solution is to use lfence just beforehand to ensure the loads are synchronized.
本文 或 这篇文章可能会提供更好的信息
This article or this article may give better info
相关文章