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

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

问题描述

考虑以下摘自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中很常见,每个内核有两个线程,因此不会算作单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天全站免登陆