简体   繁体   中英

Python multiprocessing - return when fastest process terminates

I've got a function f:

def f(param):
    return param**2

and a list of parameters p:

p = [1, 2092132192, 30912830921, 4102983092183]

(in my actual code, f POSTs to a URL specified in p and returns the response)

I want to call f on all items in p simultaneously and return the result that is the fastest and terminate the other three (or however many are still running) processes. How would I go about doing this?

Use this approach: Create a helper function which wraps f() and which doesn't return the result but puts it into a queue (maybe additionally returning it).

Now start the normal / usual process but don't wait for all threads to terminate. Instead, just wait for an item to show in the queue. If you get one, you can terminate the other threads and return.

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