简体   繁体   中英

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?

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.

Yes, you need the data to be atomic to eliminate a possibility of data race. In cases of extreme performance requirements, you might to use relaxed memory ordering when reading or writing the variable - this will ensure atomicity, but will not add ordering (if the architecture is not naturally ordered, like Intel)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM