|
| 1 | +import functools |
| 2 | +import threading |
| 3 | +import time |
| 4 | +from collections.abc import Callable |
| 5 | +from concurrent.futures import ThreadPoolExecutor, Future |
| 6 | + |
| 7 | +io_lock = threading.Lock() |
| 8 | + |
| 9 | + |
| 10 | +def print_ts(*args): |
| 11 | + with io_lock: |
| 12 | + print(*args) |
| 13 | + |
| 14 | + |
| 15 | +def print_task_completed(future: Future, task_id: str): |
| 16 | + if future.exception() is None: |
| 17 | + print_ts(f"completed") |
| 18 | + else: |
| 19 | + print_ts(f"completed with error") |
| 20 | + |
| 21 | + |
| 22 | +def dispatch_work(work: list[tuple[str, Callable]]): |
| 23 | + with ThreadPoolExecutor(max_workers=4) as executor: |
| 24 | + for task_id, func in work: |
| 25 | + future = executor.submit(func) |
| 26 | + future.add_done_callback( |
| 27 | + functools.partial(print_task_completed, task_id=task_id) |
| 28 | + ) |
| 29 | + # future.add_done_callback( |
| 30 | + # lambda fut: print_task_completed(fut, task_id) |
| 31 | + # ) |
| 32 | + |
| 33 | + |
| 34 | +def some_work(arg): |
| 35 | + time.sleep(0.0) # simulate work |
| 36 | + print_ts(arg) |
| 37 | + |
| 38 | + |
| 39 | +def main(): |
| 40 | + work = [ |
| 41 | + ("task_a", functools.partial(some_work, "A")), |
| 42 | + ("task_b", functools.partial(some_work, "B")), |
| 43 | + ("task_c", functools.partial(some_work, "C")), |
| 44 | + ("task_d", functools.partial(some_work, "D")), |
| 45 | + ] |
| 46 | + dispatch_work(work) |
| 47 | + print("all done") |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == '__main__': |
| 51 | + main() |
0 commit comments