需求:
实现函数的多线程化:
允许函数带*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()
结果:
每个函数里面都写了