繁体   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