Warm tip: This article is reproduced from serverfault.com, please click

matplotlib unstable when running in multithreading

发布于 2020-11-02 07:00:52

I'm doing a problem that obtain data from a dll to plot real time graph using matplotlib. The process run fine and able to produce real time graph. I use multi threading to obtain the data in high frequency and plot in slower rate. This is because I need a data set with 2000Hz while able to display real time.

However, the graph will stop running for a around 15 seconds while the other function that used to obtain data is running fine.

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()
Questioner
zi yang Hoe
Viewed
11
zi yang Hoe 2020-12-01 11:35:21

Update: The real time data run stable when I slice the maximum array size to 20000 for matplotlib to display each time.