什么是内存栅栏? [英] What is a memory fence?

查看:49
本文介绍了什么是内存栅栏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用显式内存栅栏是什么意思?

What is meant by using an explicit memory fence?

推荐答案

为了提高性能,现代 CPU 通常无序执行指令,以最大限度地利用可用芯片(包括内存读/写).因为硬件强制执行指令完整性,所以在单个执行线程中您永远不会注意到这一点.但是,对于具有易失性内存(例如内存映射 I/O)的多线程或环境,这可能会导致不可预测的行为.

For performance gains modern CPUs often execute instructions out of order to make maximum use of the available silicon (including memory read/writes). Because the hardware enforces instructions integrity you never notice this in a single thread of execution. However for multiple threads or environments with volatile memory (memory mapped I/O for example) this can lead to unpredictable behavior.

内存栅栏/屏障是一类指令,表示内存读/写按您预期的顺序发生.例如,完整围栏"意味着围栏之前的所有读/写都在围栏之后的内容之前提交.

A memory fence/barrier is a class of instructions that mean memory read/writes occur in the order you expect. For example a 'full fence' means all read/writes before the fence are comitted before those after the fence.

注意内存栅栏是一个硬件概念.在更高级别的语言中,我们习惯于处理互斥体和信号量 - 这些很可能在低级别使用内存栅栏来实现,并且不需要显式使用内存屏障.内存屏障的使用需要仔细研究硬件架构,在设备驱动程序中比在应用程序代码中更常见.

Note memory fences are a hardware concept. In higher level languages we are used to dealing with mutexes and semaphores - these may well be implemented using memory fences at the low level and explicit use of memory barriers are not necessary. Use of memory barriers requires a careful study of the hardware architecture and more commonly found in device drivers than application code.

CPU 重新排序与编译器优化不同 - 尽管人工制品可能相似.如果这可能导致不良行为(例如在 C 中使用 volatile 关键字),您需要采取单独的措施来阻止编译器重新排序您的指令.

The CPU reordering is different from compiler optimisations - although the artefacts can be similar. You need to take separate measures to stop the compiler reordering your instructions if that may cause undesirable behaviour (e.g. use of the volatile keyword in C).

这篇关于什么是内存栅栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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