简体   繁体   中英

Python - Properly Kill/Exit Futures Thread?

I was previously using the threading.Thread module. Now I'm using concurrent.futures -> ThreadPoolExecutor . Previously, I was using the following code to exit/kill/finish a thread:

def terminate_thread(thread):
    """Terminates a python thread from another thread.

    :param thread: a threading.Thread instance
    """
    if not thread.isAlive():
        return

    exc = ctypes.py_object(SystemExit)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(
        ctypes.c_long(thread.ident), exc)
    if res == 0:
        raise ValueError("nonexistent thread id")
    elif res > 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")

This doesn't appear to be working with futures interface. What's the best practice here? Just return ? My threads are controlling Selenium instances. I need to make sure that when I kill a thread, the Selenium instance is torn down.

Edit: I had already seen the post that is referenced as duplicate. It's insufficient because when you venture into something like futures, behaviors can be radically different. In the case of the previous threading module, my terminate_thread function is acceptable and not applicable to the criticism of the other q/a. It's not the same as "killing". Please take a look at the code I posted to see that.

I don't want to kill. I want to check if its still alive and gracefully exit the thread in the most proper way. How to do with futures?

If you want to let the threads finish their current work use:

thread_executor.shutdown(wait=True)

If you want to bash the current futures being run on the head and stop all ...future...(heh) futures use:

thread_executor.shutdown(wait=False)
for t in thread_executor._threads:
    terminate_thread(t)

This uses your terminate_thread function to call an exception in the threads in the thread pool executor. Those futures that were disrupted will return with the exception set.

How about .cancel() on the thread result?

cancel() Attempt to cancel the call. If the call is currently being executed and cannot be cancelled then the method will return False, otherwise the call will be cancelled and the method will return True.

https://docs.python.org/3/library/concurrent.futures.html

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