[英]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.alive
從bool
更改為Event
。 它們是線程安全的。 analysis_thread.queue.append(task)
,則將遇到麻煩-因為您的實現使用的是列表。 列表不是線程安全的(也許追加是原子的,但是我不確定pop
是原子的),因此您可能需要一些同步。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.