线程池 + 回调 (进程赤用法类似)

import os
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from functools import wraps

ThreadPool = ThreadPoolExecutor(max_workers=10)


def thread_executor(a):
    print("I am slave. I am working. I am going to sleep 3s")
    time.sleep(3)
    # raise "1111"
    # a = 1 + "a"
    print("Exit thread executor", a)
    return 111


def thread_task(func, *args, **kwargs):
    def worker_wrap(fn):
        @wraps(fn)
        def wrapper(*args_, **kwargs_):
            print(
                f"worker wrap. thread id: {threading.get_ident()}, "
                f"function: {fn.__name__}, args: {args_}, kwargs: {kwargs_}"
            )
            fn(*args_, **kwargs_)

        return wrapper

    def thread_callback(worker):
        worker_exception = worker.exception()
        if worker_exception:
            print(
                f"thread execute exception, thread id: {threading.currentThread().ident}, exception: {worker_exception}"
            )
        else:
            print(
                f"thread execute success. thread id: {threading.currentThread().ident}"
            )

    feature = ThreadPool.submit(worker_wrap(func), *args, **kwargs)
    feature.add_done_callback(thread_callback)
    return feature


if __name__ == "__main__":
    thread_task(thread_executor, {"a": 1, "b": 2})

posted @ 2024-06-04 17:20  一枚码农  阅读(1)  评论(0编辑  收藏  举报