cancel
Showing results for 
Search instead for 
Did you mean: 

Is it possible to interrupt the middle of a += operation?

DJC
Senior

I think I have proven now through tests that the and is clearly "YES". But, I'll still put this is as some awareness raising anyway. It might not be immediately obvious that an interrupted task can override the value of an interrupting task.

Also, I'm not 100% on my explanation of what is happening here. So someone might want to explain it in more detail.

I have a an RTOS task that does a+=n every 10ms.

I have an NVIC interrupt that does a=0; about once per minute.

"Almost always" the result of the interrupted RTOS task is that a = 0 or 1 depending on if the NVIC came before or after the += operation in the task. This is at least expected behavior in my operation.

However there is still a chance of that the NVIC task will happen during the += operation. When this happens the interrupted rtos thread in the stack still holds a stored value for a in its register. On returning to this task, the value is restored. As a result the a=0 event is overwritten.

For me a is of type double so the observed probably of this issue came out to be something like 1 in 5 days. It could take much longer if you are doing int type operations since there is a shorter amount of CPU time spent doing it.

For now I have resolved this by wrapping a

__disable_irq();

a+=n

__enable_irq();

However there are better ways such a passing a "this value was changed" type flag in another variable.

1 ACCEPTED SOLUTION

Accepted Solutions

In RISC the Load, Add and Store are separate instructions.

The variable is volatile right?

The alternative would be to have a flag, which either clears a or does a+=n when that next operation occurs.

Or instead of clearing, set b=a, and then dereference with (a-b) where you would have used the value

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..

View solution in original post

2 REPLIES 2

In RISC the Load, Add and Store are separate instructions.

The variable is volatile right?

The alternative would be to have a flag, which either clears a or does a+=n when that next operation occurs.

Or instead of clearing, set b=a, and then dereference with (a-b) where you would have used the value

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
Pavel A.
Evangelist III

/* Microcontrollers are a funny area where electronic folks meet software folks, everyone can learn something new... Software folks learn what is pull-up, hardware folks discover atomics. */