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

前端 未结 2 819
萌比男神i
萌比男神i 2020-12-11 08:45

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 syste

相关标签:
2条回答
  • 2020-12-11 09:26

    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.

    0 讨论(0)
  • 2020-12-11 09:30

    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)

    0 讨论(0)
提交回复
热议问题