[英]Run a function (in a new thread) on a subprocess that is already running
[英]How to Avoid Running a New Thread If a Thread Already Exists
如果 X 線程仍在運行,我需要運行一次 X 線程並停止生成新線程。 例如,假設我的線程是從一個名為 start_my_thread() 的函數中啟動的。
start_my_thread() 為 kline_func 啟動一個線程,該線程從遠程服務器偵聽並無限期運行,假設沒有發生網絡中斷。
def kline_func():
...
...
...
while True:
pass
def start_my_thread():
kline_thread = Thread(target = kline_func)
kline_thread.start()
start_my_thread() # first call
start_my_thread() # second call
start_my_thread() # third call
我的問題是,無論我調用 start_my_thread() 多少次,如何確保只調用一次 kline_thread.start()。 換句話說,每當我們調用 start_my_thread() 時,我想檢查我們是否有一個現有的正在運行的 kline_thread 線程。 如果我們不這樣做,則觸發 kline_thread.start()。 如果我們已經運行了 kline_thread,則不要觸發 kline_thread.start()。
我正在使用 Python3.x。 任何幫助將不勝感激。
您可以使用threading.enumerate()
函數,如文檔中所述:
返回當前活動的所有 Thread 對象的列表。 該列表包括由 current_thread() 創建的守護線程和虛擬線程對象。 它不包括已終止的線程和尚未啟動的線程。 但是,主線程始終是結果的一部分,即使在終止時也是如此
我們在初始化Thread對象的時候設置了線程名
def kline_func():
...
...
...
while True:
pass
def start_my_thread():
thread_names = [t.name for t in threading.enumerate()]
if "kline_thread" not in thread_names:
kline_thread = Thread(target = kline_func, name="kline_thread")
kline_thread.start()
start_my_thread() # first call
start_my_thread() # second call
start_my_thread() # third call
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.