Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

c++ - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...