ZhouW
ZhouW

Reputation: 1207

concurrent.futures and Flask-Executor: how to stop all future threads in a thread?

I have a Flask app that uses multithreading with the Flask-Executor package (a wrapper for concurrent.futures), and users can run jobs that may need to call a function any number of times. I want jobs to stop if the user has ran out of credits (i.e. all future threads won't run), which would be checked with a database call within a thread. Can a thread stop the executor running all future threads that would normally run?

Code example of what I'm trying to do:

def do_work(args):
    # query database to see if user_credits > 0
    if user_has_credits:
        # do work
    else:
        # shutdown executor so no future threads run - how?

from flask_executor import Executor
executor = Executor(app)
# user starts job
with app.test_request_context():
    executor.map(do_work, args) # calls do_work() function with multiple threads
executor.shutdown(wait=True)

Upvotes: 2

Views: 1446

Answers (1)

hack3r-0m
hack3r-0m

Reputation: 750

You can try

if user_has_credits:
    # do work
else:
    try:
        executor.shutdown(wait=False, cancel_futures=True) #cancel_futures is new in 3.9
    except RuntimeError:
        pass

Upvotes: 3

Related Questions