亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何讓高頻線程與低頻更新的類對話?

如何讓高頻線程與低頻更新的類對話?

慕田峪7331174 2022-06-02 16:16:32
概括我正在做一個需要低 delta_t 的實時物理模擬。我已將此模擬連接到 python-arcade 游戲窗口以實時顯示信息。我為物理線程制作了一個單獨的線程,因為物理線程中有一些昂貴的矩陣乘法。然后,當更新完成時,我設置游戲窗口類的結果狀態,游戲窗口在繪制新框架時可以顯示這些狀態。因此,我的想法是游戲窗口類只需要擔心在屏幕上的繪制,而物理線程負責所有的計算。但是,游戲窗口和線程之間的通信存在瓶頸,我不知道是否有深入的了解。我想做的最小表示:import threadingimport timeimport mathimport arcadeclass DisplayWindow(arcade.Window):    def __init__(self):        super().__init__(width=400, height=400)        self.state = 0        self.FPS = 0    def set_state(self, state):        self.state = state    def on_update(self, delta_time: float):        self.FPS = 1. / delta_time    def on_draw(self):        arcade.start_render()        arcade.draw_text(f'FPS: {self.FPS:0.2f}', 20, 20, arcade.color.WHITE)        arcade.draw_rectangle_filled(center_x=self.state * self.width,                                     center_y=self.height/2,                                     color=arcade.color.WHITE,                                     tilt_angle=0,                                     width=10,                                     height=10)# Thread to simulate physics.def simulation(display):    t_0 = time.time()    while True:        # Expensive calculation that needs high frequency:        t = time.time() - t_0        x = math.sin(t) / 2 + 0.5       # sinusoid for demonstration        # Send it to the display window        display.set_state(state=x)        # time.sleep(0.1)               # runs smoother with thisdef main():    display_window = DisplayWindow()    physics_thread = threading.Thread(target=simulation, args=(display_window,), daemon=True)    physics_thread.start()    arcade.run()    return 0if __name__ == '__main__':    main()預期結果:高幀率的平滑模擬。街機窗口只需以 30 或 60 fps 運行 on_draw。它只需要畫一些東西。實際結果:物理循環運行速度超快并調用 FPS drop。當我在物理線程中添加 time.sleep(0.1) 時,整個事情變得更加順暢,我猜出于某種原因set_state( _ )會減慢繪制循環。
查看完整描述

2 回答

?
郎朗坤

TA貢獻1921條經驗 獲得超9個贊

Python 線程可能不是您嘗試做的工作的理想工具。

盡管將 Python 線程視為并發運行可能很誘人,但事實并非如此:全局解釋器鎖 (GIL) 只允許一個線程控制 Python 解釋器。更多信息

正因為如此,該arcade.Window對象無法及早控制 Python 解釋器并運行其所有更新函數,因為 GIL 始終“專注”simulationphysics_thread.

GIL 只會在physics_thread運行一定數量的指令或使用which 在線程上執行physics_thread設置為睡眠后才釋放對 的關注并在其他線程上尋找其他事情要做。這正是您憑經驗發現的恢復程序預期行為的方法。time.sleep()

這是一個稱為線程饑餓的典型問題的示例,可以通過使用多處理庫來解決。這會帶來更多的復雜性,但會將您的 CPU 密集型計算和基于事件的輕量級接口分開在不同的進程中,從而解決您的問題。


查看完整回答
反對 回復 2022-06-02
?
拉丁的傳說

TA貢獻1789條經驗 獲得超8個贊

我研究了使用多處理而不是線程。


該multiprocessing.Pipe對象確保了雙工通信并使整個事情變得更加順暢。我現在還可以確保模擬的實時運行。


兩邊的每個更新循環,只需使用send()andrecv()命令。尚未測試邊緣情況,但似乎工作順利。


我將修改添加到上面發布的示例中:


import time

import arcade

from multiprocessing import Process, Pipe

from math import sin, pi



class DisplayWindow(arcade.Window):

    def __init__(self, connection: Pipe):

        super().__init__(500, 500)


        self.connection: Pipe = connection    # multiprocessing.Pipe


        self.position: float = 0               # GUI Display state

        self.user_input: float = 1.0           # Input to simulation

        self.FPS: float = 0                    # Frames per second estimation


    def on_update(self, delta_time: float):

        self.FPS = 1. / delta_time


        # Communicate with simulation:

        self.connection.send(self.user_input)

        self.position = self.connection.recv()


    def on_draw(self):

        arcade.start_render()

        arcade.draw_text(f'FPS: {self.FPS:0.0f}', 20, 20, arcade.color.WHITE)

        arcade.draw_point(self.position, self.height/2, arcade.color.WHITE, 10)


    def on_key_release(self, symbol: int, modifiers: int):

        if symbol == arcade.key.W:

            self.user_input = 1.8

        elif symbol == arcade.key.S:

            self.user_input = 0.3



# Separate Process target to simulate physics:

def simulation(connection: Pipe):

    t_0 = time.time()

    while True:

        freq = connection.recv() * 2 * pi       # Receive GUI user input


        t = time.time() - t_0

        x = sin(freq * t) * 250 + 250


        connection.send(x)                      # Send state to GUI


def main():

    parent_con, child_con = Pipe()

    display_window = DisplayWindow(connection=parent_con)

    physics = Process(target=simulation, args=(child_con,), daemon=True)

    physics.start()

    arcade.run()

    physics.terminate()

    return 0


if __name__ == '__main__':

    main()


查看完整回答
反對 回復 2022-06-02
  • 2 回答
  • 0 關注
  • 167 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號