asyncio: Is it possible to cancel a future been run by an Executor?

后端 未结 2 472
梦谈多话
梦谈多话 2020-11-29 10:18

I would like to start a blocking function in an Executor using the asyncio call loop.run_in_executor and then cancel it later, but that doesn\'t seem to be working for me.

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 10:34

    As threads share the same memory address space of a process, there is no safe way to terminate a running thread. This is the reason why most programming languages do not allow to kill running threads (there are lots of ugly hacks around this limitation).

    Java learnt it the hard way.

    A solution would consist in running your function in a separate process instead of a thread and terinate it gracefully.

    The Pebble library offers an interface similar to concurrent.futures supporting running Futures to be cancelled.

    from pebble import ProcessPool
    
    def function(foo, bar=0):
        return foo + bar
    
    with ProcessPool() as pool:
        future = pool.schedule(function, args=[1])
    
        # if running, the container process will be terminated 
        # a new process will be started consuming the next task
        future.cancel()  
    

提交回复
热议问题