如何理解独立C或C ++实现中的原子? [英] How to understand atomics in a freestanding C or C++ implementation?

查看:63
本文介绍了如何理解独立C或C ++实现中的原子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C11和C ++ 11根据执行线程定义原子。尽管在托管环境中很清楚什么是线程,但在独立的语言实现中它是一个模糊的术语。

C11 and C++11 define atomics in terms of threads of execution. Whereas in a hosted environment it is clear what a thread is, it is rather a vague term in a freestanding language implementation.


  1. 如何正式使用理解在独立的实现中必须在程序内部实现所有线程的C11和C ++ 11中指定的原子吗?例如:ISR是一个单独的执行线程吗?

  2. 为什么标准委员会不仅仅在代码顺序方面就根据线程而不是代码顺序来定义原子?

  3. 除gcc以外,是否已经有任何嵌入式编译器支持C11 / C ++ 11原子?


推荐答案

我对这种问题有些机械化(有些费力)的方法是,原子保证了三件事:读写不会被上下文切换所破坏(因此您只能看到实际上存储在变量中的值)。变量);缓存被刷新(因此您看不到过时的值);而且编译器无法在原子操作之间移动指令(因此,逻辑上发生在原子访问之前的操作实际上实际上发生在该访问之前)。请注意,尽管有些麻烦,但我还是尝试避免使用线程的概念。

My somewhat mechanistic (and somewhat handwaving) approach to this kind of question is that atomics guarantee three things: reads and writes won't get torn by a context switch (so you only see values that were actually stored in the variable); caches get flushed (so you don't see stale values); and the compiler can't move instructions across an atomic operation (so operations that occur logically before an atomic access in fact occur before that access). Note that I've tried to avoid any notion of "thread" here, although it gets a bit labored.

如果您正在编写自己的线程机制,则这些属性显然很重要。它们与您正在使用的线程机制的细节正交。

If you're writing your own threading mechanism, these properties are obviously important. They are orthogonal to the details of the threading mechanism that you're using.

对于信号处理程序,当您需要检查信号强度时,它们为您提供了立足之地。在信号处理程序中执行的代码以及何时信号处理程序需要修改程序其余部分关心的值。

For signal handlers, they give you a place to stand when you need to examine values from the code executed in the signal handler and when the signal handler needs to modify values that the rest of the program cares about.

我不确定标准是否正式解决了ISR (可以肯定不会),但是从这种机制的角度来看,ISR与不是来自调用 raise 的信号没有什么不同。这只是一个异步函数调用,它占用了从被中断的线程获取的堆栈空间。肯定不是不是线程;它是现有线程上的寄生虫。因此,对于ISR,我会选择信号保证而不是线程保证。

I'm not sure whether the standard formally addresses ISR's (pretty sure it doesn't), but from this mechanistic perspective, an ISR is no different from a signal that doesn't come from a call to raise. It's just an asynchronous function call, and it occupies stack space that it gets from the thread that gets interrupted. It's definitely not a thread; it's a parasite on an existing thread. So for an ISR I'd go with the guarantees for signals rather than the guarantees for threads.

这篇关于如何理解独立C或C ++实现中的原子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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