from concurrent.futures import ThreadPoolExecutor,wait,ALL_COMPLETED
from queue import Queue
myqueue = Queue() # 队列,用于保存函数运行结果。多线程的问题之一:如何保存函数运行的结果。
def thread_jobs(func, args,queue_):
'''
多线程执行入口
:param func:函数名
:param args:参数元组
:param queue_: 队列,用于保存函数运行结果
:return:
'''
threads = []
executor = ThreadPoolExecutor(max_workers=10) # 10个线程
for arg in args:
temp_arg = (arg,queue_)
t = executor.submit(func, temp_arg)
threads.append(t)
wait(threads, return_when=ALL_COMPLETED)
result = list() # 用来汇总每个线程的运行结果
while not queue_.empty():
result.append(queue_.get())
return result
target = list(range(1000))
# 最终要执行的方法
def myfunc(*args):
number = args[0][0]
queue_ = args[0][1]
print(number*2)
queue_.put(number*2)
result = thread_jobs(myfunc,target,queue_=myqueue)
print(result)