首页 > 代码库 > Python并发编程之线程池/进程池--concurrent.futures模块

Python并发编程之线程池/进程池--concurrent.futures模块

<style>h2 { color: #fff; background-color: #f7af0d; padding: 3px; margin: 10px 0px }</style>

一、关于concurrent.futures模块

  

  Python标准库为我们提供了threading和multiprocessing模块编写相应的多线程/多进程代码,但是当项目达到一定的规模,频繁创建/销毁进程或者线程是非常消耗资源的,这个时候我们就要编写自己的线程池/进程池,以空间换时间。但从Python3.2开始,标准库为我们提供了concurrent.futures模块,它提供了ThreadPoolExecutor和ProcessPoolExecutor两个类,实现了对threading和multiprocessing的进一步抽象,对编写线程池/进程池提供了直接的支持。

1.Executor和Future:

 

  concurrent.futures模块的基础是Exectuor,Executor是一个抽象类,它不能被直接使用。但是它提供的两个子类ThreadPoolExecutor和ProcessPoolExecutor却是非常有用,顾名思义两者分别被用来创建线程池和进程池的代码。我们可以将相应的tasks直接放入线程池/进程池,不需要维护Queue来操心死锁的问题,线程池/进程池会自动帮我们调度。

 

  Future这个概念相信有java和nodejs下编程经验的朋友肯定不陌生了,你可以把它理解为一个在未来完成的操作,这是异步编程的基础,传统编程模式下比如我们操作queue.get的时候,在等待返回结果之前会产生阻塞,cpu不能让出来做其他事情,而Future的引入帮助我们在等待的这段时间可以完成其他的操作。

  p.s: 如果你依然在坚守Python2.x,请先安装futures模块。

pip install futures 

 

二、操作线程池/进程池

1.使用submit来操作线程池/进程池:

# 线程池:
from concurrent.futures import ThreadPoolExecutor
import urllib.request
URLS = [http://www.163.com, https://www.baidu.com/, https://github.com/]
def load_url(url):
    with urllib.request.urlopen(url, timeout=60) as conn:
        print(%r page is %d bytes % (url, len(conn.read())))

executor = ThreadPoolExecutor(max_workers=3)

for url in URLS:
    future = executor.submit(load_url,url)
    print(future.done())

print(主线程)

# 运行结果:
False
False
False
主线程
https://www.baidu.com/ page is 227 bytes
http://www.163.com page is 662047 bytes
https://github.com/ page is 54629 bytes

  我们根据运行结果来分析一下。我们使用submit方法来往线程池中加入一个task,submit返回一个Future对象,对于Future对象可以简单地理解为一个在未来完成的操作。由于线程池异步提交了任务,主线程并不会等待线程池里创建的线程执行完毕,所以执行了print(‘主线程‘),相应的线程池中创建的线程并没有执行完毕,故future.done()返回结果为False。

# 进程池:同上
from concurrent.futures import ProcessPoolExecutor
import urllib.request
URLS = [http://www.163.com, https://www.baidu.com/, https://github.com/]
def load_url(url):
    with urllib.request.urlopen(url, timeout=60) as conn:
        print(%r page is %d bytes % (url, len(conn.read())))

executor = ProcessPoolExecutor(max_workers=3)
if __name__ == __main__: # 要加main

    for url in URLS:
        future = executor.submit(load_url,url)
        print(future.done())
    print(主线程)

#运行结果:
False  # 子进程只完成创建,并没有执行完成
False 
False
主线程 # 子进程创建完成就会向下执行主线程,并不会等待子进程执行完毕
http://www.163.com page is 662049 bytes
https://www.baidu.com/ page is 227 bytes
https://github.com/ page is 54629 bytes

2.使用map来操作线程池/进程池:

  除了submit,Exectuor还为我们提供了map方法,和内建的map用法类似:

from concurrent.futures import ThreadPoolExecutor
import urllib.request
URLS = [http://www.163.com, https://www.baidu.com/, https://github.com/]
def load_url(url):
    with urllib.request.urlopen(url, timeout=60) as conn:
        print(%r page is %d bytes % (url, len(conn.read())))

executor = ThreadPoolExecutor(max_workers=3)

executor.map(load_url,URLS)

print(主线程)

# 运行结果:
主线程
http://www.163.com page is 662047 bytes
https://www.baidu.com/ page is 227 bytes
https://github.com/ page is 54629 bytes

  从运行结果可以看出,map是按照URLS列表元素的顺序返回的,并且写出的代码更加简洁直观,我们可以根据具体的需求任选一种。

 

3.wait:

  wait方法接会返回一个tuple(元组),tuple中包含两个set(集合),一个是completed(已完成的)另外一个是uncompleted(未完成的)。使用wait方法的一个优势就是获得更大的自由度,它接收三个参数FIRST_COMPLETED, FIRST_EXCEPTIONALL_COMPLETE,默认设置为ALL_COMPLETED。

  如果采用默认的ALL_COMPLETED,程序会阻塞直到线程池里面的所有任务都完成,再执行主线程:

from concurrent.futures import ThreadPoolExecutor,wait,as_completed
import urllib.request
URLS = [http://www.163.com, https://www.baidu.com/, https://github.com/]
def load_url(url):
    with urllib.request.urlopen(url, timeout=60) as conn:
        print(%r page is %d bytes % (url, len(conn.read())))

executor = ThreadPoolExecutor(max_workers=3)

f_list = []
for url in URLS:
    future = executor.submit(load_url,url)
    f_list.append(future)
print(wait(f_list))

print(主线程)

# 运行结果:
http://www.163.com page is 662047 bytes
https://www.baidu.com/ page is 227 bytes
https://github.com/ page is 54629 bytes
DoneAndNotDoneFutures(done={<Future at 0x2d0f898 state=finished returned NoneType>, <Future at 0x2bd0630 state=finished returned NoneType>, <Future at 0x2d27470 state=finished returned NoneType>}, not_done=set())
主线程

  如果采用FIRST_COMPLETED参数,程序并不会等到线程池里面所有的任务都完成。

from concurrent.futures import ThreadPoolExecutor,wait,as_completed
import urllib.request
URLS = [http://www.163.com, https://www.baidu.com/, https://github.com/]
def load_url(url):
    with urllib.request.urlopen(url, timeout=60) as conn:
        print(%r page is %d bytes % (url, len(conn.read())))

executor = ThreadPoolExecutor(max_workers=3)

f_list = []
for url in URLS:
    future = executor.submit(load_url,url)
    f_list.append(future)
print(wait(f_list,return_when=FIRST_COMPLETED))

print(主线程)

# 运行结果:
http://www.163.com page is 662047 bytes
DoneAndNotDoneFutures(done={<Future at 0x2bd15c0 state=finished returned NoneType>}, not_done={<Future at 0x2d0d828 state=running>, <Future at 0x2d27358 state=running>})
主线程
https://www.baidu.com/ page is 227 bytes
https://github.com/ page is 54629 bytes

 

 

  ?写一个小程序对比multiprocessing.pool(ThreadPool)和ProcessPollExecutor(ThreadPoolExecutor)在执行效率上的差距,结合上面提到的Future思考为什么会造成这样的结果?

 

Python并发编程之线程池/进程池--concurrent.futures模块