Created
February 20, 2025 18:40
-
-
Save galatolofederico/91cdb84b9b101a80b376035b234414d6 to your computer and use it in GitHub Desktop.
Run multiple tasks concurrently and return the result of the first one that completes without using async/await
This file contains hidden or 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 | |
| def first_completed(f, args, num_workers=10): | |
| executor = concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) | |
| try: | |
| futures = [executor.submit(f, *arg) for arg in args] | |
| ret = None | |
| for future in concurrent.futures.as_completed(futures): | |
| ret = future.result() | |
| break | |
| for future in futures: | |
| future.cancel() | |
| executor.shutdown(wait=False) | |
| return ret | |
| except: | |
| executor.shutdown(wait=False) | |
| raise | |
| if __name__ == "__main__": | |
| import time | |
| import random | |
| def f(i, n): | |
| print(f"{i}) I will sleep for {n:.5f} seconds") | |
| time.sleep(n) | |
| return n | |
| fastest = first_completed(f, [(i, random.random()) for i in range(0 ,10)]) | |
| print(f"The fastest job took: {fastest:.5f} seconds") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment