Created
March 30, 2024 22:39
-
-
Save normanlmfung/539de6aac65d00911f363b5fc847afd7 to your computer and use it in GitHub Desktop.
python_syntax_concurrent_futures_ThreadPoolExecutor_task_chaining
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 | |
import time | |
def background_task1(): | |
item_list = [] | |
for i in range(10): | |
item_list.append(i) | |
time.sleep(1) | |
# Simulate an exception being thrown | |
raise ValueError("Simulated exception") | |
return item_list | |
def background_task2(item_list): | |
for item in item_list: | |
print(f"{item}") | |
def handle_completed_task1(future): | |
try: | |
item_list = future.result() | |
background_task2(item_list) # Task chaining: Less elegant syntax compared to C# TPL ContinueWith | |
except Exception as e: | |
print(f"Background task failed: {str(e)}") | |
def main(): | |
with concurrent.futures.ThreadPoolExecutor() as executor: | |
future1 = executor.submit(background_task1) | |
future1.add_done_callback(handle_completed_task1) | |
# Wait for both futures to complete | |
concurrent.futures.wait([future1]) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment