multithreadingsynchronizationproducer-consumerlock-freebuffering

How to correctly implement triple buffering?


I am trying to simulate videocard (producer thread) and a monitor(consumer thread), to figure out what is going on in educational purposes. So here is the technical task description:

Producer thread produces frames pixel data at 1000 fps. Consumer thread runs at 60 fps and every frame it must have access to last produced frame for at least 1/60th of second. Each frame is represented by some int*, for simplicity.

So my solution is that i have array of 2 pointers: one for producer, one for consumer. And plus some free, unused pointer, which is not owned by consumer or producer at any given moment of time.

#define Producer 0
#define Consumer 1
int* usedPointers[2];
std::atomic<int*> freePointer;

Correct me if i am wrong.

I miss what is memorySemanticsXXX. There are descriptions but i cannot figure out which exactly should i use in every thread and why. So i am asking for some hints on that.


Solution

  • memorySemanticsXXX you're mentioning are about the rest of your code surrounding the exchange() lines. The default behavior for std::atomic::exchange() is that memory_order_seq_cst is used (the second parameter for exchange() you're not using).

    This means three things at the same time:

    So, the whole point is that you may choose not to have one, two or all three of these restrictions, which can bring you speed improvements. You shouldn't bother with this unless you have a performance bottleneck. If there's no bottleneck then just use std::atomic without the second parameter (it will take the default value).

    In case you don't use all three restrictions you have to be really careful writing your code otherwise it can unpredictably crash.

    Read more about it here: Memory order