I am working on DoCplex problem in which I have 2 models. I am using ThreadPoolExecutor() to run the solves parallel. But is it possible to kill one of the solve once one of them is complete? I am using following code:
def work(slvr):
print("This is worker", slvr)
# do stuff
mdl= slvr.solve(clean_before_solve=True,log_output=True)
return mdl
with concurrent.futures.ThreadPoolExecutor() as executor:
future_to_area = {executor.submit(work, slvr): slvr for slvr in a}
for future in concurrent.futures.as_completed(future_to_area):
id = future_to_area[future]
I think this is unrelated to docplex but is a more general question: Running multiple threads, how can you terminate all remaining threads as soon as the first thread finishes?
One option for doing this would be to create one additional thread that receives the future_to_area
map (so it must be created after all the docplex threads were submitted). Also create a variable winner
that is proteced by a condition variable. Once a docplex thread has finished, it sets winner
to its id or future and signal the condition variable.
The additional thread waits on the condition variable unless winner
becomes non-None
. As soon as this is not None
, it knows that one of the docplex threads finished. At this point if stops all other threads in future_to_area
by calling cancel()
on the respective future.