0

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]

1 Answers1

0

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.

Daniel Junglas
  • 5,830
  • 1
  • 5
  • 22
  • Thanks for replying, I am able to stop the thread using Queue and threads but the solver keep running and keep returning solver log even to spyder stop executing. But I think I can make that work – Kartik Kaushik Sep 04 '20 at 15:48
  • Maybe you have to add an aborter to each solver thread and then use that aborter to explicitly abort the solve. Then before cancelling the future, you can trigger that aborter. – Daniel Junglas Sep 07 '20 at 04:57
  • That's a good idea, but I tried using AutomaticAborter but I can't update it once the solver has started. Any ideas to how to add aborter? – Kartik Kaushik Sep 08 '20 at 16:25
  • I don't know what an `AutomaticAborter` is but what you have to do is to use a docplex-specific aborter that can abort the native code of the solver. I think you may have to call the solver object's `get_cplex()` method and then install an aborter into that low-level object. I suggest you either check the CPLEX Python API reference documentation for that or create a new question asking "how to *asynchronously* abort a solve in docplex?". – Daniel Junglas Sep 09 '20 at 04:29