Python多线程结合嵌套字典实现树莓派Zero多传感器分刷新率采集的问题求解
核心问题根源
你遇到的参数串值问题本质是Python列表属于可变引用类型,所有线程共享了同一个properties_list内存对象,并非传递独立的值拷贝,具体触发逻辑:
- 循环第一次遍历
test传感器时,将其属性写入公共properties_list,创建线程时传入的是这个列表的内存引用,而非列表当时的内容快照 - 你紧接着进入下一轮传感器遍历,直接调用
properties_list.clear()清空列表,再塞入dht传感器的属性 - 受操作系统线程调度延迟影响,第一个启动的
test传感器线程,往往不会在你调用clear()之前就执行目标函数读取参数。等线程真正需要读取properties_list内容时,原列表已经被清空、写入了第二轮遍历的dht传感器属性,最终就出现第一个线程拿到第二个传感器参数的异常 - 这也是为什么你改成串行逻辑运行正常的原因:串行执行时线程目标函数会立刻读取参数,还没等到下一轮循环修改
properties_list,就已经拿到了完整的属性值。
问题直接修复方案
只需要在给线程传参时,传递当前properties_list的独立副本,而非原对象引用,就能立刻解决串值问题:
- 核心修改:把线程参数里的
properties_list,替换为properties_list.copy()或list(properties_list),每个线程拿到的是和当前循环迭代绑定的专属列表副本,后续清空、修改原列表的操作,都不会影响已经传给线程的副本
修改后的循环代码:
properties_list = [] thread_list = [] for sensor, value in sensors.items(): for properties in value: properties_list.append(value[properties]) # 关键修改:传入列表的独立拷贝 thread = threading.Thread( target=read_sensor_value, args=[ sensor, refresh_rate_sensor[sensor], properties_list.copy(), db ] ) thread_list.append(thread) thread.start() properties_list.clear() for thread in thread_list: thread.join()
注意:只要传入的参数是可变对象(列表、字典、自定义对象),多线程传参时都要确认是否需要做值拷贝,否则后续对原对象的修改会同步影响所有持有该引用的线程。
适配树莓派场景的优化实现方案
结合你的传感器采集需求,手动拼装properties_list的实现存在冗余,还容易触发引用类bug,更贴合实际运行场景的优化方向如下:
- 去掉手动拼装属性列表的中间逻辑,直接把每个传感器对应的配置字典当线程参数传递,代码和原始配置结构对齐,降低维护成本
- 避免跨线程共享SQLite数据库连接:SQLite连接默认不支持多线程并发访问,跨线程共享极易触发数据库锁、读写异常的问题,改为每个采集线程内部初始化独立的数据库连接
- 给采集线程设置为守护线程,适配树莓派上长期运行的采集服务场景,主程序退出时能自动终止所有采集线程,不需要额外写终止逻辑
优化后的参考代码:
import threading import time def sensor_collect_worker(sensor_name, refresh_interval, sensor_config, db_path): # 每个线程独立初始化数据库连接,避免跨线程共享 db = connect_database(db_path) try: # 按指定刷新率持续循环采集 while True: # 采集传感器数值的逻辑放在这里 collected_data = read_sensor_data(sensor_config) # 写入数据库的逻辑放在这里 write_record_to_db(db, sensor_name, collected_data) time.sleep(int(refresh_interval)) except Exception as e: print(f"传感器{sensor_name}采集异常:{str(e)}") finally: db.close() def main(): db_save_path = 'sensors.db' sensors, refresh_rate_sensor = read_sensor_configuration() thread_list = [] # 逐传感器启动采集线程 for sensor_name, sensor_config in sensors.items(): interval = refresh_rate_sensor[sensor_name] thread = threading.Thread( target=sensor_collect_worker, args=(sensor_name, interval, sensor_config, db_save_path), daemon=True # 设为守护线程,主程序退出时自动终止 ) thread_list.append(thread) thread.start() # 阻塞主程序,保持采集运行 for thread in thread_list: thread.join()
这套方案的优势:
- 从根源规避引用串值问题:遍历过程中传入的传感器配置是读配置生成的静态字典,后续循环不会修改该字典内容,不存在参数被后续迭代覆盖的风险
- 适配树莓派的硬件资源限制:线程逻辑轻量,每个传感器的采集间隔独立设置,不会互相阻塞
- 解决了SQLite多线程读写的常见稳定性问题,适合树莓派上长期无人值守运行的采集场景
内容的提问来源于stack exchange,提问作者Rysiusek
相关产品推荐
相关产品推荐

