簡體   English   中英

如何使用阻塞命令殺死python中的線程?

[英]How to kill a thread in python with blocking command?

我想使用 Interactive Brokers 的 API,它在不同的線程上打開 TCP 連接。 問題是 app.run() 需要調用來建立 TCP 連接的函數可能使用一個 while true 循環來處理它的隊列,這會阻止我知道在退出程序時終止線程的所有可能方式。

class TradeApp(EWrapper, EClient): 
    def __init__(self): 
        EClient.__init__(self, self)
    #...

def websocket_con():
    app.run()
    
app = TradeApp()      
app.connect("127.0.0.1", 7497, clientId=1)
con_thread = threading.Thread(target=websocket_con, daemon=True)
con_thread.start()

我試過使用一個守護線程和一個簡單的線程。 我也嘗試過使用事件。 但無論我做什么,似乎線程永遠不會退出 app.run() 函數的執行。

class TradingApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
    #...

def websocket_conn():
    app.run()
    event.wait()
    if event.is_set():
        app.close()

event = threading.Event()
app = TradingApp()
app.connect("127.0.0.1", 7497, clientId=1)

conn_thread = threading.Thread(target=websocket_conn)
conn_thread.start()

#...

event.set()

難道我做錯了什么? 如何退出 app.run() 函數?

我認為你不了解多處理,當你通過新進程啟動websocket_conn()函數時,這個新進程將逐步執行,所以event.wait() if event.is_set():app.run()之前不執行還沒有結束。

嘗試這樣的事情:

conn_thread = threading.Thread(target=websocket_conn)
conn_thread.start()

event.wait()
if event.is_set():
        conn_thread.kill()

暫無
暫無

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

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