Handling Non-Atomic Operations for 64-bit Variables on a 32-bit Non-Preemptive System

Hi everyone, @Middleware & OS I'm struggling to find sufficient material on handling non-atomic operations, and I'd appreciate some guidance. I need to maintain a microsecond count in a 64-bit variable, with a 32-bit processor system that uses a non-preemptive scheduler. An ISR will update this variable every microsecond. My system provides functions to clear the variable and read its value. Since the processor is 32-bit, accessing the entire 64-bit variable atomically might not be possible. Concerned how I can ensure that the read function doesn't retrieve a partially updated value as in reading half from the old value and half from the new value during an interrupt? In non-preemptive scheduling context now, are there standard approaches to guarantee consistent reads of the 64-bit variable? If so, could anyone help me on some of these techniques?
Solution:
Yeah, you are right @Marvee Amasi 👍... @Sterling try to disable interrupts during the read operation to prevent the ISR from updating the variable while you're reading it.This will enable you to read either the old or new value in its entirety.
Jump to solution
6 Replies
Marvee Amasi
Marvee Amasi6mo ago
I know double buffering is a common technique for handling non atomic operations. You can create two 32-bit variables buffer_a and buffer_b and use them as a double buffer. ISR would update one buffer say buffer_a with the new microsecond count. The read function would access the other buffer buffer_b . You can then toggle between which buffer the ISR writes to and which the read function accesses so that a complete value is always read, even if ISR updates the other buffer during the read operation
Sterling
Sterling6mo ago
Hmm, okay okay... Makes sense, Thanks for this @Marvee Amasi 🙏
Marvee Amasi
Marvee Amasi6mo ago
Yh you welcome @Sterling you know you can temporarily disable interrupts around the update operation in the ISR and the read operation in your main code
Sterling
Sterling6mo ago
To give me exclusive access to the variable during these critical sections
Solution
UC GEE
UC GEE6mo ago
Yeah, you are right @Marvee Amasi 👍... @Sterling try to disable interrupts during the read operation to prevent the ISR from updating the variable while you're reading it.This will enable you to read either the old or new value in its entirety.
Marvee Amasi
Marvee Amasi6mo ago
Okay yh re enable interrupts after the operation is complete !! But pls use this approach with caution cus disabling interrupts for too long can make your system unresponsiveness
Want results from more Discord servers?
Add your server