# Swapping arrays for an interrupt, quickly

**URL:** <https://forum.arduino.cc/t/swapping-arrays-for-an-interrupt-quickly/1152089>\
**Category:** Programming\
**Created:** [July 26, 2023, 10:11pm UTC](https://forum.arduino.cc/t/swapping-arrays-for-an-interrupt-quickly/1152089 "2023-07-26T22:11:05Z")\
**Posts on this page:** 1\
**Showing post:** 17

<div class="post-metadata">

**Author:** ![PieterP](https://avatars.discourse-cdn.com/v4/letter/p/ecccb3/32.png) [@PieterP](https://forum.arduino.cc/u/PieterP)\
**Post date:** [August 8, 2023, 5:58pm UTC](https://forum.arduino.cc/t/swapping-arrays-for-an-interrupt-quickly/1152089/17 "2023-08-08T17:58:29Z")

</div>

> [@J-M-L](#):
>
> `__sync_synchronize()`

This might be okay on AVR, since `__sync_synchronize()` is only a compile-time fence (in the absence of caches, out-of-order execution, multiple cores, etc.).  
However, on non-AVR targets, you should use the standard library atomics and fences, e.g. [std::atomic\_signal\_fence - cppreference.com](https://en.cppreference.com/w/cpp/atomic/atomic_signal_fence).  
This is because C++ has a well-defined memory model, and rigorously defines the behavior and synchronization and memory order guarantees for all atomic operations and fences.

A full memory fence like `__sync_synchronize()` is serious overkill: for interrupt handlers, you should only need compile-time barriers. (\*)  
Even for multithreaded applications, you only need atomic exchange/load-acquire and store-release operations to implement a mutex, not full barriers. See e.g. [Correctly Implementing a Spinlock in C++ | Erik Rigtorp](https://rigtorp.se/spinlock/)

In the context of interrupts, a mutex is essentially useless, because the ISR cannot possibly acquire it without deadlocking.

* * *

(\*) Since both the access of the volatile variable `mutexFlag` and the call to `(no)interrupts()` (access of a volatile register) have observable side effects, you don't need any additional ordering constraints in this case.  
However, `volatile` does not guarantee any memory order, so it cannot be used for multithreaded applications.

---

_[View the full topic](https://forum.arduino.cc/t/swapping-arrays-for-an-interrupt-quickly/1152089)._
