I am having a working code, but not really sure that this is the right way. I have two functions, both making an API request that can take an arbitrary time between 1 and 5 seconds, but both are designed to return the same output. I want to run the two simultaneously and once the quicker finished its job, terminate the other and drop whatever it would return.
p1 = Process(target = search1, args=(name) )
p2 = Process(target = search2, args=(name) )
if __name__=='__main__':
p1.start()
p2.start()
while p1.is_alive() and p2.is_alive():
time.sleep(0.2)
if not p1.is_alive():
p2.terminate()
if not p2.is_alive():
p1.terminate()
If I do not wait some time (0.2 seconds in this case) sometimes both are returning if both take somewhat the same time. I tested many times and it works, but is this the right way doing this? Is there any issue that can surface with this approach?
--- ti7 suggestion
Trying with threading after ti7's suggestion, now it works with threadings rather than Processes.
def search1(Q_result, name):
result = somefunction()
Q_result.put(result)
def search2(Q_result, name):
time.sleep(10)
result = somefunction()
Q_result.put(result )
import Queue as queue
import threading
Q_result = queue.Queue() # create a Queue to hold the result(s)
if __name__=='__main__':
t1 = threading.Thread(
target=search1,
args=(Q_result, name),
)
t1.daemon = True
t1.start()
t2 = threading.Thread(
target=search2,
args=(Q_result),
)
t2.daemon = True
t2.start()
print(Q_result.get())