Skip to content

Instantly share code, notes, and snippets.

@normanlmfung
Last active June 10, 2024 02:07
Show Gist options
  • Save normanlmfung/fc246d2afde6cdc12230a8610b45c590 to your computer and use it in GitHub Desktop.
Save normanlmfung/fc246d2afde6cdc12230a8610b45c590 to your computer and use it in GitHub Desktop.
python_syntax_concurrent_futures_ThreadPoolExecutor
import concurrent.futures
import time
def background_task(task_id):
item_list = []
for i in range(3):
item_list.append((task_id, i))
time.sleep(1)
return item_list
def task_done_callback(future):
try:
result = future.result()
print("Background task completed with result:", result)
except Exception as e:
print("Background task raised an exception:", e)
def main():
tasks = []
# With ThreadPoolExecutor, you can control pool size
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
for i in range(3): # Submitting 3 background tasks
future = executor.submit(background_task, i)
future.add_done_callback(task_done_callback)
tasks.append(future)
print("Main thread continues execution while background tasks are running...")
print("Waiting for background tasks to complete...")
for task in tasks:
try:
task.result() # This will wait for each task to complete. This will re-raise any exception caught during the task execution.
except Exception as task_err:
print(f"{task_err}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment