实现:多线程 + 线程返回结果 + 返回线程run的异常状态

需求:
实现函数的多线程化:
允许函数带*args和**kwargs输入参数
多线程 + 线程返回结果 + 返回线程run的异常状态

代码实现:

import threading
import traceback


class ThreadItWithResult(threading.Thread):
    """发送请求作为线程,返回一个请求结果"""

    def __init__(self, func, *args, **kwargs):
        super(ThreadItWithResult, self).__init__()
        self.setDaemon(True)
        self.func = func
        self.args = args
        self.kwargs = kwargs
        self.result = None

    def run(self):
        try:
            self.result = self.func(*self.args, **self.kwargs)
        except Exception as e:
            print(str(traceback.format_exc()))
            print(f"{e}")

    def get_result(self):
        # 线程不结束,返回值为None
        try:
            return self.result
        except Exception as e:
            print(f"e: {e}")
            print(str(traceback.format_exc()))
            return None


class ThreadItWithResultException(ThreadItWithResult):
    """返回结果包含异常状态(捕获每个线程的异常状态)"""

    # def __init__(self, func, *args, **kwargs):
    #     super(ThreadItWithResultException, self).__init__(func, *args, **kwargs)

    def run(self):
        try:
            self.result = self.func(*self.args, **self.kwargs), True
        except Exception as e:
            print(str(traceback.format_exc()))
            print(f"{e}")
            self.result = f"{e}", False


def func_test(a, b, c, d="test"):
    ret = a + b + c
    return ret


def thread_it_without_order():
    t_list = []
    a1, b1, c1 = 1, 2, 3
    for i in range(2):  # TWS的话,全部是左通道(左右耳的左通道)
        t = ThreadItWithResultException(func_test, a1, b1, c1, d="test")
        t.start()
        t_list.append(t)
    for t in t_list:
        t.join()
        ret, except_state = t.get_result()
        print(f"ret: {ret}")
        if not except_state:
            raise Exception(ret)
    # 测试结果:
    # ret: 6
    # ret: 6


def thread_it_without_order_v1():
    t_list = []
    a1, b1, c1 = 1, 2, 3
    for i in range(2):  # TWS的话,全部是左通道(左右耳的左通道)
        t_list.append(ThreadItWithResultException(func_test, a1, b1, c1, d="test"))
    for t in t_list:
        t.start()
    for t in t_list:
        t.join()
        ret, except_state = t.get_result()
        print(f"ret: {ret}")
        if not except_state:
            raise Exception(ret)
    # 测试结果:
    # ret: 6
    # ret: 6


def thread_it_with_order():
    a1, b1, c1 = 1, 2, 3
    a2, b2, c2 = 11, 22, 33
    t1 = ThreadItWithResultException(func_test, a1, b1, c1, d="test")
    t2 = ThreadItWithResultException(func_test, a2, b2, c2, d="test")
    t_dict = {
        "1": t1,
        "2": t2
    }
    for t in t_dict.values():
        t.start()
    dict_ret = dict()
    for l_r, t in t_dict.items():
        t.join()
        ret, except_state = t.get_result()
        if not except_state:
            raise Exception(ret)
        else:
            dict_ret[l_r] = ret

    ret_1 = dict_ret["1"]
    ret_2 = dict_ret["2"]

    print(f"ret_1, ret_2: {ret_1, ret_2}")

    # 测试结果:
    # ret_1, ret_2: (6, 66)


if __name__ == '__main__':
    # thread_it_without_order()
    # thread_it_without_order_v1()
    thread_it_with_order()

结果:
每个函数里面都写了

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值