Atomic newbie here. My code currently looks like this (simplified):
std::atomic<Object*> object;
void thread_a()
{
object.load()->doSomething(); // (1)
}
void thread_b()
{
Object* oldObject = object.load();
Object* newObject = new Object();
// Update new object accordingly...
while (!object.compare_exchange_weak(oldObject, newObject));
delete oldObject;
}
In words, my idea is to let thread_b
atomically swap the shared object (double-buffering), while thread_a
performs some work on it. My question: can I safely assume that the shared object will be "protected" against data races while thread_a
calls doSomething()
on it, as done in (1)?
Double buffering is a term used to describe a device with two buffers. The usage of multiple buffers increases the overall throughput of a device and helps prevents bottlenecks. For example, with graphics, double buffering can show one image or frame while a separate frame is being buffered to be shown next.
A programming technique that uses two buffers to speed up a computer that can overlap I/O with processing. Data in one buffer are being processed while the next set of data is read into the other one.
There are two buffers in the system. One buffer is used by the driver or controller to store data while waiting for it to be taken by higher level of the hierarchy. Other buffer is used to store data from the lower level module. Double buffering is also known as buffer swapping.
In computer graphics, double buffering is a technique for drawing graphics that shows no (or less) stutter, tearing, and other artifacts. It is difficult for a program to draw a display so that pixels do not change more than once.
The fetching of the pointer with load()
will be atomic, but the call to doSomething()
itself will not be atomic.
That means the pointers could be swapped after load()
is called but before doSomething()
is called (which means doSomething()
is called on the wrong and now deleted object).
Perhaps a mutex could be a better choice here?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With