简体   繁体   中英

How to kill a thread in python with blocking command?

I want to use Interactive Brokers' API which opens a TCP connection on a different thread. The problem is that the app.run() function what needs to be called to establish the TCP connection probably uses a while true loop for processing it's queue, what block every possible way I know to terminate the thread when exiting the program.

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()

I've tried using a daemon thread and simple one. I've tried to use events also. But whatever I do, it seems the thread will never exit from the execution of app.run() function.

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()

Am I doing something wrong? How could I exit from app.run() function?

I think u bad understand multiprocessing, when u start websocket_conn() function by new process, this new process will be executed step by step so event.wait() if event.is_set(): doesn't execute before app.run() wasn't over.

Try something like this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM