python - Return whichever expression returns first -



python - Return whichever expression returns first -

i have 2 different functions f, , g compute same result different algorithms. 1 or other takes long time while other terminates quickly. want create new function runs each simultaneously , returns result first finishes.

i want create function higher order function

h = firstresult(f, g)

what best way accomplish in python?

i suspect solution involves threading. i'd avoid give-and-take of gil.

now - unlike suggestion on other answer, piece of code requesting:

from multiprocessing import process, queue import random import time def firstresult(func1, func2): queue = queue() proc1 = process(target=func1,args=(queue,)) proc2 = process(target=func2, args=(queue,)) proc1.start();proc2.start() result = queue.get() proc1.terminate(); proc2.terminate() homecoming result def algo1(queue): time.sleep(random.uniform(0,1)) queue.put("algo 1") def algo2(queue): time.sleep(random.uniform(0,1)) queue.put("algo 2") print firstresult(algo1, algo2)

python multithreading concurrency

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -