C ++“内存屏障"的示例包括: [英] Example of C++ "Memory barrier"

查看:137
本文介绍了C ++“内存屏障"的示例包括:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关volatile关键字的问题的答案:

I was reading the answer to this question regarding the volatile keyword:

https://stackoverflow.com/a/2485177/997112

此人说:

防止重新排序的解决方案是使用内存屏障, 向编译器和CPU都表明没有内存访问 在这一点上可能会重新排序.在我们周围放置这样的障碍 易失性变量访问可确保即使是非易失性访问也不会 在易失性变量之间重新排序,使我们能够编写线程安全的 代码.

The solution to preventing reordering is to use a memory barrier, which indicates both to the compiler and the CPU that no memory access may be reordered across this point. Placing such barriers around our volatile variable access ensures that even non-volatile accesses won't be reordered across the volatile one, allowing us to write thread-safe code.

但是,内存屏障还可以确保所有挂起的读/写操作都是 在达到障碍时执行,所以它有效地给了我们 我们自己需要的所有东西,因此不需要挥发.我们可以 完全删除易失性限定符.

However, memory barriers also ensure that all pending reads/writes are executed when the barrier is reached, so it effectively gives us everything we need by itself, making volatile unnecessary. We can just remove the volatile qualifier entirely.

如何在C ++中实现这种内存屏障"?

How is this "memory barrier" implemented in C++?

有人可以举一个简单的代码示例吗?

推荐答案

这是非常依赖于硬件的.从相当长的Linux内核的内存障碍文档:

This is very hardware-dependent. From the fairly long documentation of memory barrier of the Linux kernel:

The Linux kernel has eight basic CPU memory barriers:

TYPE                MANDATORY               SMP CONDITIONAL
===============     ======================= ===========================
GENERAL             mb()                    smp_mb()    
WRITE               wmb()                   smp_wmb()
READ                rmb()                   smp_rmb()   
DATA DEPENDENCY     read_barrier_depends()  smp_read_barrier_depends()

让我们特别考虑其中之一:smp_mb(). 如果打开asm/x86/um/asm/barrier.h,您会发现在定义CONFIG_SMP后,

Let's take one of them in particular: smp_mb(). If you open asm/x86/um/asm/barrier.h, you will find that when CONFIG_SMP is defined,

#define smp_mb()    mb()

如果向上滚动,您会看到mb取决于平台,mb具有不同的实现:

And if you scroll up, you can see that depending on the platform, mb has different implementations:

// on x86-32
#define mb()        alternative("lock; addl $0,0(%%esp)", "mfence", X86_FEATURE_XMM2)
// on other platforms
#define mb()        asm volatile("mfence" : : : "memory")

有关这两件事之间差异的更多信息,已在此线程中进行了讨论.我希望这会有所帮助.

More information on the differences between these 2 things have been discussed in this thread. I hope this helps.

这篇关于C ++“内存屏障"的示例包括:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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