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

问题描述

我正在为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:44