本文介绍了我需要保护一个由一个线程写入并由许多读取的变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我在写一个数据采集系统。该系统既处理来自我们的信号数字化仪的快速数据,又缓慢地控制/监测诸如检测器的高压系统。慢速控制系统每秒读取一次电压,并将它们写入数据结构。 每个事件在写入磁盘之前都标有检测器的电压。要做到这一点,事件处理线程读取由慢控制/监视线程写的结构。 考虑到事件发生后X微秒电压读取标记有前一秒的电压读取:我需要麻烦一个互斥保护结构中的数据结构或原子变量 解决方案如果我理解正确,每隔一个线程读取电压,写入一些数据结构,其他线程每隔一段时间从这个数据结构读取如果这个数据结构有原子加载和存储( int , char 等等),因为其他线程正在读取的值将永远不会改变(或者其他讨厌的事情可能发生,例如重新排序)。您需要同步以确保原子存储/加载从其内存存储而不是从缓存存储正确读/写。 如果此数据结构不是原子 - 然后我们处理未定义的行为,这总是错误的。 所以你需要使数据结构原子和同步,通过原子 如果这个数据结构足够小, std :: atomic 。如果没有,看看你的系统是否支持读写器锁,他们似乎极端适合这里。 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. 这篇关于我需要保护一个由一个线程写入并由许多读取的变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-20 23:30