Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform double buffering with atomic pointers?

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)?

like image 892
Ignorant Avatar asked Oct 30 '18 09:10

Ignorant


People also ask

How does double buffering work?

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.

What is double buffering in C++?

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.

Who are the two participants in the buffer swap?

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.

What problem does double buffering solve?

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.


Video Answer


1 Answers

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?

like image 164
Some programmer dude Avatar answered Sep 21 '22 05:09

Some programmer dude