自定义线程类
# ThreadMinx.py
class MyThread(threading.Thread):
def __init__(self, func, args=()):
super(MyThread, self).__init__()
self.func = func
self.args = args
self.func_name = func.__name__
def run(self):
self.result = self.func(*self.args)
def get_result(self):
try:
return self.result
except Exception as e:
return None
创建线程
import ThreadMinx
from threading import Lock
lo = Lock()
def func1():
time.sleep(7)
return "func1"
def func2():
time.sleep(6)
return "func2"
def func3():
time.sleep(2)
return "func3"
def func4():
time.sleep(1)
return "func4"
def func5():
time.sleep(3)
return "func5"
if __name__ == "__main__":
import time
start = time.time()
# 创建多个线程
threads = [func1, func2, func3, func4, func5]
a = []
for t in threads:
t = ThreadMInx.MyThread(t)
a.append(t)
t.start()
for t in a:
t.join()
for t in a:
# 获取先线程调用的func名称以及func返回值
print("res", t.get_result(), t.func_name)
print(time.time() - start)
|