本文介绍了可以原子地读取压缩结构内的变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 Cortex M0 (ARM) CPU 编写代码,并且 32 位读/写是原子的.现在我想知道当我读/写 8bit/16bit 变量时,它们是否也保证是原子的?我的直觉是肯定的,因为它们在内部对齐到 32 位部分,因此 CPU 不可能需要两条单独的指令来读取/写入它们.

I'm writing code for a Cortex M0 (ARM) CPU, and 32-bit reads/writes are atomic. Now I was wondering when I read/write 8bit/16bit variables, are they also guaranteed to be atomic? My instinct says yes, because they are internally aligned to 32-bit sections, so there is no possibility that the CPU needs two separate instructions to read/write them.

但我也碰巧在压缩结构中存储了很多变量以节省内存,并且有可能变量没有在 32 位边界上对齐,因此 16 位值的每一半可能在不同的部分.

But I also happen to store a lot of variables in packed structures to save memory, and there it's possible that variables are not aligned on 32-bit boundaries, so each half of a 16-bit value could be in a different section.

那么当我使用压缩结构时我会丢失原子操作是真的吗?

So is it true that I lose atomic operations when I use packed structures?

推荐答案

使用压缩结构,您将永远不会对与内存单元边界重叠的字段进行读/写原子操作.这意味着只有 8 位操作才能保证是原子的,否则取决于您的字段的内存对齐方式.

Using packed structures you will never have read/write atomic operations on fields that overlaps a memory unit boundary. This means that only 8bits operations are guaranteed to be atomic, otherwise it depends on the memory alignment of your fields.

这篇关于可以原子地读取压缩结构内的变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 15:43