python 使用thread多线程执行耗时代码
1、引入所需要的包
import queue
import threading
import traceback
2、定义线程类:
class ThreadService(threading.Thread):
def __init__(self, queue, out_dict):
super(ThreadService, self).__init__()
self.queue = queue
self.out_dict = out_dict
def run(self):
while True:
try:
data = 耗时的方法(self.queue)
self.out_dict[self.queue] = data
except queue.Empty:
break
except:
print(traceback.format_exc())
break
@classmethod
def cal_thread_num(cls, task_num, per_thread_num=5, max_thread_num=200):
if task_num <= per_thread_num:
return 1
return min(task_num, int(task_num / per_thread_num), max_thread_num)
3、定义调用线程类
标签:thread,python,self,list,queue,num,多线程,out From: https://www.cnblogs.com/yangbeita/p/17010727.html
class LoadBundleService(object):
@classmethod
def loard(cls, req_list):
out_dict = {}
path_queue = queue.Queue()
for v in req_list:
path_queue.put(v)
thread_list = []
thread_num = ThreadService.cal_thread_num(task_num=len(req_list))
for i in range(thread_num):
t = ThreadService(path_queue)
thread_list.append(t)
# 启动线程
for t in thread_list:
t.start()
# 等待线程结果
for t in thread_list:
t.join()
# 输出结果
return thread_list[0].out_dict