在多线程中 运行 时 matplotlib 不稳定

matplotlib unstable when running in multithreading

我正在做一个从 dll 获取数据以使用 matplotlib 绘制实时图形的问题。该过程 运行 很好并且能够生成实时图形。我使用多线程以高频获取数据并以较慢的速率绘制。这是因为我需要一个2000Hz的数据集,同时又能实时显示。

但是,图表将停止 运行ning 大约 15 秒,而用于获取数据的另一个函数 运行ning 正常。

import sys
import ctypes as ct
import time
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
from matplotlib.animation import FuncAnimation
import threading

mod_name = r"G:\software\datalite\OnLineInterface.dll"
# mod_name = "kernel32"
OnLineInterfaceDll = ct.WinDLL(mod_name)
OnLineStatus = OnLineInterfaceDll.OnLineStatus
OnLineStatus.argtypes = (ct.c_long, ct.c_long, ct.POINTER(ct.c_long))
a = ct.c_long(0)
b = ct.c_long(2)
c = ct.c_long()
OnLineStatus(a, b, ct.pointer(c))

xcache = []
ycache = []

def GetData():
    i = 0
    b = ct.c_long(1)
    v = 0


    b = ct.c_long(4)

    while i < 5000000 :
        OnLineStatus(a, b, ct.pointer(c))
        cconv = ((c.value - 4000) / 1000)
        print(cconv)
        v = time.perf_counter()
        print("time:", v)

        xcache.append(v)
        ycache.append(cconv)

        i += 1

def DrawData():
    figure, ax = plt.subplots(figsize=(8, 6))
    plt.title("EMG signal", fontsize=25)
    plt.xlabel("time(seconds", fontsize=18)
    plt.ylabel("EMG(mV)", fontsize=18)


    def animate(i):
        plt.cla()
        plt.plot(xcache, ycache)
        print(xcache)


    ani = FuncAnimation(plt.gcf(), animate, 1000)
    plt.show()

if __name__ == "__main__":

    t1 = threading.Thread(target=GetData)
    t2 = threading.Thread(target=DrawData)
    t1.start()
    t2.start()
    t1.join()
    t2.join()

更新: 实时数据运行每次将最大数组大小切片为20000供matplotlib显示时稳定