Atomic access for 16-byte structure
Atomic access for 16-byte structure
Hi! I have a timespec struct (defined in <time.h>) in my C project, built with gcc-rx (v8.3.0.202405) and newlib-nano. It contains a long long seconds counter (8 bytes) and a long long nsec counter (8 bytes too.) The timer is incremented by an MTU interrupt, and various application timers read this as needed. This is simply a free-running counter that will “never” overflow in practice.
I need to guarantee atomicity of the structure reads/writes, as interrupts and the application are separate “threads”. I define my cpu_time using _Atomic (defined in <stdatomic.h>) and gcc compiles fine. I need to write/read this variable using copy instructions, as expected. Accessing the struct members of the _Atomic struct generates a compiler error, which is also expected. So, gcc seems to “know” what it’s dealing with.
The issue is at link time. __atomic_load and __atomic_store are not found (“undefined reference.”) I’m not 100% sure if newlib-nano supports these. If so, what am I missing, and if not, are there any known light-weight libs out there I could use?
Thanks!
Hello,
We are glad to hear that a solution has been found – and thank you for sharing it with the other users!
Please let us know if we can be of assistance with any other issues.
Best regards,
The Open Source Tools Team
Hello jltrahan
I must admit I don’t see how use of an XCHG lock can solve the problem?
The problem, as I understand it:
- An interrupt makes a read-modify-write of the time structure.
- A main call graph function access the time structure (can be interrupted in the middle of the copy)
- I assume that your interrupt cannot just return when the lock is taken, as the update (add) will be lost?
Therefore the access function must disable interrupts before access (copy) and restore the interrupt after the access. Like this:
- __builtin_rx_clrpsw(‘I’); // Disable int
- copy_time_to_private_variable();
- __builtin_rx_setpsw(‘I’); // Enable int
BR. Frank
OK, found a solution for this if anybody else has the same question. With the RX FIT library (i.e. Smart Configurator) you also get an XCHG based lock/unlock routines, which are fine for my application (see r_bsp_locking.h/.c)