使用concurrent.futures模块,这个模块是python3中自带的模块,但是,python2.7以上版本也可以安装使用(pip install futures
),具体使用方式如下,直接上代码:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from concurrent.futures import ThreadPoolExecutor
import time
def func(a):
print(a)
time.sleep(0.1)
li = ["a","b","c","d","e"]
for循环,顺序执行,速度慢
start1 = time.time()
for obj in li:
func(obj)
end1 = time.time()
print("time1: "+str(end1-start1))
线程池,示例1
start2 = time.time()
with ThreadPoolExecutor(3) as executor:
for obj in li:
executor.submit(func,obj)
# 如果是多个参数,直接在后面添加
# executor.submit(func,a,b,c,d,e)
end2 = time.time()
print("time2: "+str(end2-start2))
线程池,示例2
start3 = time.time()
with ThreadPoolExecutor(3) as executor1:
executor1.map(func,li)
end3 = time.time()
print("time3: "+str(end3-start3))
注意:在使用多线程时,如果涉及到操作共享数据,需要加锁。
文档
https://docs.python.org/zh-cn/3/library/concurrent.futures.html