3
\$\begingroup\$

On the AVR XMEGA, or any AVR, is it safe to do pointer operations, like passing by reference and accessing pointers while interrupts are on? I keep feeling like I need to wrap each pointer operation into an ATOMIC_BLOCK() macro. Is this necessary? Also, I need to copy a structure with like 30 bytes of data, should this be in an ATOMIC_BLOCK()?

The AVR address bus is 16 bits, and takes two cycles to access a pointer, correct?

\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

Why are you worried about pointers in particular? They are really just variables like any other.

The key issue with concurrency, such as between non-interrupt code and interrupt code, is when you have two concurrent threads that access, or more importantly, modify the same variable (whether it is a pointer or not). It is those shared variables that you need to consider protecting, especially if the operations on them are not intrinsically atomic.

Operations on non-shared variables (or pointers, or structures) do not need any special treatment.

If you do share a pointer between concurrent threads, keep in mind that any data that the pointer points to also needs to be considered "shared data" and needs to be given the same considerations.

\$\endgroup\$
3
  • \$\begingroup\$ I guess I was thinking of the scenario where you are using a pointer in the main code or using a multibyte variable like uint16, and an interrupt fires. The operation could be interrupted in the middle and go to the interrupt ISR. Will the AVR pick up where it left off, or does the AVR deference the pointer or complete the uint16+ operation and then go to the ISR \$\endgroup\$ Commented Oct 5, 2016 at 15:58
  • \$\begingroup\$ Even if a non-atomic operation on a variable is interrupted in the middle, it will return and continue correctly -- unless the interrupt has failed to fully restore the state of the CPU, in which case, the interrupt code needs to be fixed! \$\endgroup\$
    – Dave Tweed
    Commented Oct 5, 2016 at 16:04
  • 1
    \$\begingroup\$ @zacharoni16 The AVR will back up and restore any modified state information perfectly, interrupts would be near useless if that wasn't the case. You only have to be concerned about atomic access to a variable (pointers are not special, they are variables as well) if your interrupt service routine can modify the pointer being modified/Dereferenced. I would also avoid using pointers on an XMEGA, as array indexing is generally faster and you can even fit an index into a single char. \$\endgroup\$
    – jms
    Commented Oct 5, 2016 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.