Created
September 17, 2019 20:10
-
-
Save ixe013/d92fff14f2f5a45d4c4adef4d5523107 to your computer and use it in GitHub Desktop.
Aborting a thread pool executor using events. Some threads will never run (that's what we want to demonstrate)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import concurrent.futures | |
import logging | |
import threading | |
import time | |
import random | |
def return_after_5_secs(num, stop): | |
threading.current_thread().name = f"banane{num}" | |
logging.debug(f"from inside {num}") | |
if not stop.isSet(): | |
print(f'{num:4d} a) started') | |
if stop.wait(random.randint(1, 5)): | |
print(f'{num:4d} b) cancelled') | |
else: | |
return f'{num:4d} c) never started' | |
return f"{num:4d} c) returned" | |
def main(): | |
stop = threading.Event() | |
pool = concurrent.futures.ThreadPoolExecutor(5) | |
futures = [] | |
for x in range(15): | |
futures.append(pool.submit(return_after_5_secs, x, stop)) | |
try: | |
count = 0 | |
for x in concurrent.futures.as_completed(futures, timeout=5): | |
count = count + 1 | |
print(x.result()) | |
if count > 3: | |
stop.set() | |
except concurrent.futures.TimeoutError as te: | |
print(f'Timeout {te}') | |
stop.set() | |
pool.shutdown(False) | |
if __name__ == '__main__': | |
logging.basicConfig(format='%(asctime)s %(levelname)s t:%(threadName)s %(message)s [%(filename)s:%(lineno)d]', level=logging.DEBUG) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment