3

I wonder if it would be possible to write std::atomic<> for the use on the AVR µC. The __atomic_xxx() built-ins are unfortunately not implemented in avr-gcc.

As I understand basic load/store of uint8_t on AVR is atomic, but e.g. operator++() not because it implies an rmw-cycle. So, for these operations one has to disable interrupts, because this is the only form of concurrency on this hardware. For larger types than uint8_t even the operator=(T) needs to be protected from interrupts.

On the other hand one has to apply a memory-barrier to the data member of the std::atomic<> template: e.g. this data member has the name value one has to use asm volatile("" : "+m" (value)); to accomplish real load/stores on the machine.

Is this sufficient to implement the std::atomic<>?

Because this implementation is lock-free, it should be useable for ISRs on that hardware.

If one would implement such std::atomic<> this would led to unefficient machine code inside the ISR, because the unneccessary interrupt disabling and/or the memory-barrier, which prevents optimization.

Well, this could be circumvented by extending the interface of the std::atomic<> with unsafe operations.

On the other hand: would it be more feasable to implement std::atomic_ref<> and use this outside the ISR?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
wimalopaan
  • 4,838
  • 1
  • 21
  • 39
  • 2
    Using `asm volatile ("" : "+m" (value));` would be sufficient for `relaxed` atomic operations, and it shouldn't do unnecessary harm to optimization because operations on other variables can be moved and optimized around it. But for acquire/release or stronger ordering, you would need `asm volatile("" : : : "memory");` to get a full compiler barrier. – Nate Eldredge Feb 15 '23 at 18:21
  • I guess a lazy way to get "unsafe" operations would be the reverse of `atomic_ref`: a member function that just returns a reference to the object as an ordinary non-atomic `int&` or whatever. In practice you can probably get this already with a simple type cast. – Nate Eldredge Feb 15 '23 at 18:29

0 Answers0