运行环境:python 3.6.0
1、过去:
使用threadpool模块,这是个python的第三方模块,具体使用方式如下:
# -*- encoding: utf-8 -*-
import threadpool
import time
def sayhello (a):
print("hello: " + a)
time.sleep(2)
def main():
global result
seed = ["a", "b", "c"]
""" 多线程 """
start = time.time()
task_pool = threadpool.ThreadPool(5)
requests = threadpool.makeRequests(sayhello, seed)
for req in requests:
task_pool.putRequest(req)
task_pool.wait()
end = time.time()
time_m = end - start
print("time: " + str(time_m))
""" 单线程 """
start1 = time.time()
for each in seed:
sayhello(each)
end1 = time.time()
print("time1: " + str(end1 - start1))
if __name__ == '__main__':
run()
main()
# 运行结果
"""
hello: a
hello: b
hello: c
over
hello: a
hello: b
hello: c
time: 2.022491216659546
hello: a
hello: b
hello: c
time1: 6.006936311721802
"""
threadpool是一个比较老的模块了,现在虽然还有一些人在用,但已经不再是主流了,关于python多线程,现在已经开始步入未来(future模块)了。
2、未来:
使用concurrent.futures模块,这个模块是python3中自带的模块,但是,python2.7以上版本也可以安装使用,具体使用方式如下:
# -*- encoding: utf-8 -*-
from concurrent.futures import ThreadPoolExecutor
import time
def sayhello(a):
print("hello: " + a)
time.sleep(2)
def main():
seed = ["a", "b", "c"]
""" 单线程 """
start1 = time.time()
for each in seed:
sayhello(each)
end1 = time.time()
print("time1: " + str(end1-start1))
""" 多线程<submit> """
start2 = time.time()
with ThreadPoolExecutor(3) as executor:
for each in seed:
executor.submit(sayhello, each)
end2 = time.time()
print("time2: " + str(end2 - start2))
""" 多线程<map> """
start3 = time.time()
with ThreadPoolExecutor(3) as executor1:
executor1.map(sayhello, seed)
end3 = time.time()
print("time3: " + str(end3 - start3))
if __name__ == '__main__':
main()
# 输出结果
"""
hello: a
hello: b
hello: c
time1: 6.018568754196167
hello: a
hello: b
hello: c
time2: 2.006592035293579
hello: a
hello: b
hello: c
time3: 2.0062594413757324
"""
注意到一点:
concurrent.futures.ThreadPoolExecutor,在提交任务的时候,有两种方式,一种是submit()函数,另一种是map()函数,两者的主要区别在于:
1. map可以保证输出的顺序, submit输出的顺序是乱的
2. 如果你要提交的任务的函数是一样的,就可以简化成map。但是假如提交的任务函数是不一样的,或者执行的过程之可能出现异常(使用map执行过程中发现问题会直接抛出错误)就要用到submit()
3. submit和map的参数是不同的,submit每次都需要提交一个目标函数和对应的参数,map只需要提交一次目标函数,目标函数的参数放在一个迭代器(列表,字典)里就可以。