Python3中Multiprocessing配合FuncAnimation实时绘图无更新问题求助
问题修复方案
以下是代码存在的核心问题及修复方法:
- 共享内存写入逻辑错误:你在
run_server函数中直接对shared_data_time、shared_data_signal做赋值操作,本质是把本地变量重新指向了新的numpy数组,完全没有写入多进程共享的内存区域,主进程自然读不到更新的数据,需要改用切片赋值写入共享内存。 - 数据类型不匹配:你从socket接收的数据解析为
float64(8字节)类型,但创建共享数组时用的是'f'(对应float32,4字节),类型不匹配会导致数据乱码、长度错误。 - 绘图函数未正确读取共享数据:
matplotlib的plot方法不能直接识别multiprocessing.Array对象,需要先转换为numpy数组或普通列表再绘图。
修正后完整代码
import socket import sys import math import numpy as np import struct import time import os import ctypes as c import multiprocessing import matplotlib.pyplot as plt from matplotlib import animation from matplotlib import style HOST = '127.0.0.1' PORT = 6543 receive_size = 4096 def run_server(shared_data_time, shared_data_signal): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server: server.bind((HOST, PORT)) server.listen() conn, addr = server.accept() with conn: print(f"Connected by {addr}") while True: data = conn.recv(receive_size) if len(data) == 4096: payload = np.frombuffer(data, dtype = 'float64') print(payload) print('received data') deinterleaved = [payload[idx::2] for idx in range(2)] # 改用切片赋值写入共享内存,同时转换类型匹配共享数组 shared_data_time[:] = deinterleaved[0].astype('float32') shared_data_signal[:] = deinterleaved[1].astype('float32') print(f'received {len(data)} bytes') if __name__ == '__main__': HOST = '127.0.0.1' PORT = 6543 receive_size = 4096 shared_data_time = multiprocessing.Array('f', 2048) shared_data_signal = multiprocessing.Array('f', 2048) process1 = multiprocessing.Process(target = run_server, args =(shared_data_time, shared_data_signal)) process1.start() def animate(i, shared_data_time, shared_data_signal): ax1.clear() # 将共享数组转换为numpy数组再绘图 ax1.plot(np.asarray(shared_data_time), np.asarray(shared_data_signal)) style.use('fivethirtyeight') fig = plt.figure() ax1 = fig.add_subplot(1,1,1) ani = animation.FuncAnimation(fig, animate, fargs = (shared_data_time, shared_data_signal), interval = 100) plt.show()
内容的提问来源于stack exchange,提问作者Victor Robles Fernández
相关产品推荐
相关产品推荐

