簡體   English   中英

在單獨的線程中運行while循環以檢查后台任務

[英]Running a while loop in a separate thread to check for background tasks

這會是一個不好的做法,還是有另一種更好的方法來做這種事情? 我目前所擁有的程序具有一個CLI菜單系統,可以接收用戶輸入,並基於該輸入將在數據庫中查詢數據並對其進行分析。

但是,我想做的是使用日期時間設置該查詢以使其啟動,然后將其添加到隊列中。 理想情況下,我會將其置於菜單系統的事件循環中,但是菜單系統在等待用戶輸入時暫停(通過內置的python input功能或通過curses window.getkey函數)。 另外,我希望在分析數據時仍然能夠使用菜單

因此,我正在使用兩個線程,一個用於檢查隊列中是否有日期時間小於datetime.now() ,將其從隊列中刪除,進行分析,然后繼續檢查隊列。

class AnalysisQueue(threading.Thread):
    def __init__(self, initial_queue):
        super(AnalysisQueue, self).__init__()
        self.alive = True
        self.queue = initial_queue

    def run(self):
        while self.alive: #loop can be terminated externally
            for i,object in enumerate(self.queue):
                if datetime.now() > object.analysis_start:
                    analyse_data(self.queue.pop(i)) #defined elsewhere


class Menu(threading.Thread):
    def __init__(self):
        super(Menu, self).__init__()
        self.date_menu = MultipleChoiceMenu([
            {'description': "Test1"},
            {'description': "Test2"},
            {'description': "Test3"},
        ]) #Menu class that handles display and I/O for the menu

    def run(self):
        self.date_menu.input() #initializes the menu display and waits for input

analysis_thread = AnalysisQueue()
menu_thread = Menu()

analysis_thread.start()
menu_thread.start()
menu_thread.join() #waits for the menu thread to finish (menu is exited)
analysis_thread.alive = False 
#Now that menu has been exited, terminate program.
#whether or not the queue has entries in it at this point is not a concern 

這種方法有什么問題,還是有更好的方法呢?

謝謝你的幫助!

這是一個開放性問題,更像是代碼審查,但這是我的反饋:

  • 您可以使用優先級隊列,而不用遍歷整個列表以查找時間戳。 然后,您只需要查看隊列的開頭即可。
  • self.alivebool更改為Event 它們是線程安全的。
  • 對我來說,這似乎是一個常規的工作隊列,通常用於保持GUI線程的響應速度。 但是,我不了解您時間戳記的原因-為什么不立即運行任務?
  • 您如何將分析結果傳達回主線程?
  • 不包括用於將任務追加到隊列的代碼。 如果您只是在執行analysis_thread.queue.append(task) ,則將遇到麻煩-因為您的實現使用的是列表。 列表不是線程安全的(也許追加是原子的,但是我不確定pop是原子的),因此您可能需要一些同步。
  • 也許您可以嘗試將排隊和工作線程的邏輯分開。

結論。 我會像您一樣設置一個工作人員,並安排一個常規的任務Queue 也許是一個好的開始?

暫無
暫無

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

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