为什么内存重新排序在单核/处理器机器上不是问题? [英] Why memory reordering is not a problem on single core/processor machines?

查看:28
本文介绍了为什么内存重新排序在单核/处理器机器上不是问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下取自 Wikipedia 的示例,稍作修改,其中程序的步骤对应于各个处理器指令:

Consider the following example taken from Wikipedia, slightly adapted, where the steps of the program correspond to individual processor instructions:

x = 0;
f = 0;

Thread #1:
   while (f == 0);
   print x;

Thread #2: 
   x = 42;
   f = 1;

我知道,由于无序执行,当线程在两个不同的物理内核/处理器上运行时,print 语句可能会打印不同的值(42 或 0).

I'm aware that the print statement might print different values (42 or 0) when the threads are running on two different physical cores/processors due to the out-of-order execution.

但是我不明白为什么这在单核机器上不是问题,因为这两个线程在同一个核心上运行(通过抢占).根据 维基百科:

However I don't understand why this is not a problem on a single core machine, with those two threads running on the same core (through preemption). According to Wikipedia:

当程序在单 CPU 机器上运行时,硬件会执行必要的簿记,以确保程序执行时就像所有内存操作都按照程序员指定的顺序(程序顺序)执行,因此内存屏障不会必要的.

When a program runs on a single-CPU machine, the hardware performs the necessary bookkeeping to ensure that the program executes as if all memory operations were performed in the order specified by the programmer (program order), so memory barriers are not necessary.

据我所知,单核 CPU 也会重新排序内存访问(如果它们的内存模型很弱),那么如何确保程序顺序得以保留?

As far as I know single-core CPUs too reorder memory accesses (if their memory model is weak), so what makes sure the program order is preserved?

推荐答案

CPU 不会意识到这是两个线程.线程是一种软件构造 (1).

The CPU would not be aware that these are two threads. Threads are a software construct (1).

所以 CPU 按以下顺序看到这些指令:

So the CPU sees these instructions, in this order:

store x = 42
store f = 1
test f == 0
jump if true ; not taken
load x

如果 CPU 将 x 的存储重新排序到最后,在加载之后,它会改变结果.虽然允许 CPU 乱序执行,但它只有在不改变结果时才会这样做.如果允许这样做,几乎每个指令序列都可能失败.不可能产生一个工作程序.

If the CPU were to re-order the store of x to the end, after the load, it would change the results. While the CPU is allowed out of order execution, it only does this when it doesn't change the result. If it was allowed to do that, virtually every sequence of instructions would possibly fail. It would be impossible to produce a working program.

在这种情况下,不允许单个 CPU 在加载相同地址后重新排序存储.至少,就 CPU 可以看到它没有重新排序.就 L1、L2、L3 缓存和主内存(以及其他 CPU!)而言,可能尚未提交存储.

In this case, a single CPU is not allowed to re-order a store past a load of the same address. At least, as far the CPU can see it is not re-ordered. As far the as the L1, L2, L3 cache and main memory (and other CPUs!) are concerned, maybe the store has not been committed yet.

(1) 诸如 HyperThreads 之类的东西,每个核心两个线程,在现代 CPU 中很常见,不会被视为 w.r.t 的单 CPU".你的问题.

(1) Something like HyperThreads, two threads per core, common in modern CPUs, wouldn't count as "single-CPU" w.r.t. your question.

这篇关于为什么内存重新排序在单核/处理器机器上不是问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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