Python: concurrent.futures How to make it cancelable?

后端 未结 3 1952
-上瘾入骨i
-上瘾入骨i 2020-12-03 13:50

Python concurrent.futures and ProcessPoolExecutor provide a neat interface to schedule and monitor tasks. Futures even provide a .cancel() method:

3条回答
  •  失恋的感觉
    2020-12-03 14:50

    Unfortunately, running Futures cannot be cancelled. I believe the core reason is to ensure the same API over different implementations (it's not possible to interrupt running threads or coroutines).

    The Pebble library was designed to overcome this and other limitations.

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

提交回复
热议问题