Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to guard a variable that is written by one thread and read by many?

I am writing a data acquisition system. The system is both handling fast data from our signal digitizers, and slow controls/monitoring for things like the high voltage system for the detectors. The slow control system reads the voltages once per second and writes them to a data structure.

Each event is tagged with the voltage for its detector prior to being written to disk. To do this the event processing threads read the structure written by the slow control / monitoring thread.

Given that it doesn't matter if an event that occurred X microseconds after a voltage read is tagged with the previous second's voltage read: Do I need bother with a mutex to guard the data structure or atomic variables in the structure?

like image 762
James Matta Avatar asked Feb 08 '23 06:02

James Matta


1 Answers

If I understand correctly, every second one thread is reading the voltage, writes it to some "data structure" and other threads are reading from that data structure every now and then (am I correct?)

if this "data structure" has atomic loads and stores (int,char, etc. on x86, for example) than it may be possible that the value that other threads are reading will never change (or other nasty things may happen, like reordering). you need synchronization to make sure that atomic store/load is correctly read/written from its memory storage rather than from cached storage.

if this "data structure" is not atomic - then we're dealing with undefined behaviour, and this is wrong always.

so you do need to make the "data structure" both atomic and synchronized, either by atomics, either by locks.

if this "data structure" is small enough, std::atomic seems suitable here. if not, see if your system supports reader-writer locks, they seems extremly suitable here.

like image 92
David Haim Avatar answered Feb 16 '23 04:02

David Haim