How can I abort a task in a multiprocessing.Pool after a timeout?

前端 未结 2 1707
粉色の甜心
粉色の甜心 2020-12-08 03:10

I am trying to use the multiprocessing package of python in this way:

featureClass = [[1000,k,1] for k in drange(start         


        
2条回答
  •  心在旅途
    2020-12-08 04:05

    we can use gevent.Timeout to set time of worker running . gevent tutorial

    from multiprocessing.dummy import Pool 
    #you should install gevent.
    from gevent import Timeout
    from gevent import monkey
    monkey.patch_all()
    import time
    
    def worker(sleep_time):
        try:
    
            seconds = 5  # max time the worker may run
            timeout = Timeout(seconds) 
            timeout.start()
            time.sleep(sleep_time)
            print "%s is a early bird"%sleep_time
        except:
            print "%s is late(time out)"%sleep_time
    
    pool = Pool(4)
    
    pool.map(worker, range(10))
    
    
    output:
    0 is a early bird
    1 is a early bird
    2 is a early bird
    3 is a early bird
    4 is a early bird
    8 is late(time out)
    5 is late(time out)
    6 is late(time out)
    7 is late(time out)
    9 is late(time out)
    

提交回复
热议问题