簡體   English   中英

如何在函數之間實時共享變量

[英]How to share variables real time between functions

我有一個軟件工程項目(使用python),最終目標是實時繪制數據。 為簡單起見,假設我有這兩個單獨的函數,一個函數用於生成數據,另一個函數使用matplotlib實時繪制(剛剛生成的)數據,問題是我如何讓這兩個並行運行的函數共享同一變量?

我研究了multiprocessing ,並且兩個函數同時運行。 但是,我無法讓他們實時共享數據。 這是我所擁有的:

import time
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random
import multiprocessing as mp


def live_graph():
    # Create figure for plotting
    fig1 = plt.figure(1)
    ax1 = fig1.add_subplot(1, 1, 1)
    xs = []
    ys_temperature = []

    # This function is called periodically from FuncAnimation
    def animate_temperature(i, xs, ys_temperature):
        # Add x and y to lists
        xs.append(dt.datetime.now().strftime('%H:%M:%S.%f'))
        ys_temperature.append(random.randint(-55, 55))

        # Limit x and y lists to 20 items
        xs = xs[-20:]
        ys_temperature = ys_temperature[-20:]

        # Draw x and y lists
        ax1.clear()
        ax1.plot(xs, ys_temperature)

        # Format plot
        plt.xticks(rotation=45, ha='right')
        plt.subplots_adjust(bottom=0.30)
        plt.title('Temperature over Time')
        plt.ylabel('Temperature (deg C)')

    ani_temperature = animation.FuncAnimation(fig1, animate_temperature, fargs=(xs, ys_temperature), interval=1000)

    plt.show()


def gen_data():
    while True:
        temperature = random.randint(500, 1000)
        print(temperature)
        time.sleep(1)


if __name__ == '__main__':

    one = mp.Process(target=gen_data)
    two = mp.Process(target=live_graph)

    one.start()
    two.start()

現在, live_graph函數只是在繪制任意數據。 我希望它能繪制由gen_data函數生成的數據。 任何提示或方向將不勝感激!

幾種方法取決於您所遇到的確切問題:

  1. 使用線程而不是多處理。 並行進程不會共享相同的上下文,因此不會共享變量。 但是,線程允許這樣做。 但是在Python中,您將遭受GIL問題的困擾,如果一個線程被I / O綁定而另一個線程被CPU綁定,則可能不必擔心。

  2. 有關跨進程使用隊列的示例,請參見https://docs.python.org/3.4/library/multiprocessing.html#exchanging-objects-between-processes 您的數據是單向傳遞的,因此一個隊列就足夠了。

  3. 使用諸如消息隊列服務器之類的工具。如果可以預見到程序可以大規模發展,那么使用多層體系結構就可以考慮使用這種方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM