Is it necessary to protect reads of volatile variables in critical sections when using interrupts? Or are critical sections only required when concurrently writing variables?
Here is an example of a variable written within an ISR which is protected with a critical section:
void loop() {
portENTER_CRITICAL(&mux);
uint other = variable_written_from_isr + 1;
portEXIT_CRITICAL(&mux);
}
What will happen if an interrupt changes variable_written_from_isr
while it is being read? Would anything worse that inconsistencies happen?
Here is an opposite example where a variable is written from an interrupt and read from the loop (or a task):
void IRAM_ATTR handleInterrupt() {
portENTER_CRITICAL_ISR(&mux);
uint other = variable_written_from_loop + 1;
portEXIT_CRITICAL_ISR(&mux);
}
Please note that I aware of stdatomic. I am mainly interested in understanding the behavior of concurrent access in the context of interrupts.
What will happen if an interrupt changes variable_written_from_isr while it is being read?
..... there will be no interrupt becauseportENTER_CRITICAL(&mux);
disables interrupts