Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
10 years, 8 months ago.
Is swapping pointers atomic (double buffering)?
I'm in a situation where I'd like to have a Thread produce some information, and a Ticker consume the latest version of that information. Now, obviously the possibility of the Ticker interrupting the producer thread in the middle of producing information is very real, so I'm thinking the producer thread needs to generate information into a back buffer while the consumer interrupt operates on a front buffer (double buffering). Once the producer thread is finished, it swaps the buffer pointers and starts over.
So my question is: is swapping pointers an atomic operation, or do I need to temporarily disable interrupts while I swap them?
4 Answers
10 years, 8 months ago.
Hi Neil,
Generally, swapping pointers is not an atomic operation. There are other ways to implement what you're looking for, see for example https://en.wikipedia.org/wiki/Circular_buffer
HTH, Bogdan
10 years, 8 months ago.
Hello Neil,
once I faced similar problem, I used "quite simple" ring buffer (not certain by double buffering you mean the same). There are some thread-safe ring buffers implementation. Allocate enough size so the producer won't be overwriting data (will be consumed fast enough).
I don't believe swapping pointers is an atomic operations. Why would you disable interrupts and "hold" entire system when I assume are using mbed RTOS and got available synchronization primitives?
Regards,
0xc0170
Interesting, I'll have to look into that. I think the proper term for what I was describing is a ping-pong buffer, where both buffers take turns being the front and back buffer. Since the consumer is an interrupt, I don't think I can use any of the synchronization primitives in the RTOS, unless maybe Mutex.trylock() still works from an interrupt context...
posted by 03 Apr 2014