内存屏障/栅栏如何禁止 CPU 执行指令重新排序? [英] How memory barrier/fence inhibit instruction reordering carried out by CPU?

查看:113
本文介绍了内存屏障/栅栏如何禁止 CPU 执行指令重新排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,编译器和CPU都可以进行指令重新排序.由 CPU 执行",我的意思是我不关心由编译器完成的指令重新排序以及由存储缓冲区和 CPU 缓存引起的重新排序.对于由 Store Buffer 和 CPU Cache 引起的重新排序,在 这篇论文,我已经理解了内存屏障是如何抑制这种重新排序的(memory reordering).

So far as I know,both compiler and CPU can carry out instruction reordering. By 'carried out by CPU',I mean that I do not care about instruction reordering that is done by compiler and reordering that is caused by Store Buffer and CPU cache. For reordering caused by the Store Buffer and CPU Cache,which was discussed in this paper, I have already understood how memory barrier inhibit such reordering(memory reordering).

我关心的是这样的重新排序:

What I care is such a reordering:

源代码:

data=1; //statement1
ready=true;//statement2

但是,运行在 CPU0 上的 ThreadA 按以下顺序执行上述代码:

But, ThreadA run on CPU0 executes the above code in the following order:

ready=true;//statement2
data=1; //statement1

也就是说CPU对指令重新排序,导致实际执行顺序与源代码指定的顺序不同.众所周知,如果我们想保持源代码的顺序,我们可以求助于内存屏障(或栅栏),如:

That's to say the CPU reorders the instructions,which causes the actual execution order different from the order specified by source code. As we know,if we want to make the order of source code be preserved, we can resort to memory barrier(or fence),as:

新源代码:

data=1; //statement1
smp_wb();//Insert a write barrier here!
ready=true;//statement2

所以我的问题来了:内存屏障是如何禁止指令在这里重新排序的?

So here comes my question: how memory barrier inhibit instruction reordering here?

推荐答案

@Tsyvarev 是正确的,它是特定于处理器(或处理器系列)的.例如,在 ARM 下,DMB(内存屏障)会导致 CPU 管道停顿以确保排序(防止重新排序),因为它的 文档 说:

@Tsyvarev is correct, it is processor(or processor family) specific. For example, under ARM, the DMB(a memory barrier) causes a stall of the CPU pipeline to ensure ordering(prevents reordering),as its documentation said:

图 1 显示了用于确保内存的 DMB 指令通过暂停管道进行排序

Figure 1 shows the DMB instruction being used to ensure memory ordering by stalling the pipeline

这篇关于内存屏障/栅栏如何禁止 CPU 执行指令重新排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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