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

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

问题描述

使用显式内存栅栏意味着什么?

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天全站免登陆