How do you synchronize copies of the data between threads?


Usually I was doing thread syncs (UI->audio and audio->UI) using atomic flags, shared_ptr and fifos assuming only one of the threads write data. There were no problems with that.

However, how do you sync in a lockfree way some complex data (think in a sequence of notes and events where you can add or remove elements) when both thread can read or write on them? I thought different solutions, but I’m not satisfied with them:

  1. Using two FIFOs to notify changes between cloned datas. However this may be problematic. Assuming I read one FIFO at the beginning of the processblock and the other one in a timer, the audio thread could write a “delete blob Z” (in the fifo and its own audio data) while the message thread could write a “modify blob Z” (in its fifo and its own ui data)… depending which one comes first it I could have different results, even some de-synchronization or bug. (I could use weak_ptr here to check).

  2. Using a FIFO for audio->UI, and a dirty flag for ui->audio. The UI is reading the fifo with a 40ms timer, and it prepares a copy of the full data for the audio thread. The audio thread checks at the begging if there are new data to deprecate the old one. The problem with this approach is that the changes you do in the audio thread to the data will have a delay! This is a problem for noteOn which won’t be played.

I can think in other solutions, but all of them seem tedious and prone to have bugs. Is there a better method?

Have you watched these amazing talks from @fr810 and @dave96 ?

1 Like

I’d also recommend these talks, I have the slides bookmarked for easy access:

1 Like

Thank you for the tips, I’ve seen a lot of videos like those, but I didn’t watch these ones. I seems I’m in the harder case judging by the scale/diagram I saw in the slides :smiley: I’ll try to find some tips there