1. 程式人生 > >Python併發程式設計之執行緒池/程序池

Python併發程式設計之執行緒池/程序池

Python併發程式設計之執行緒池/程序池

2017/01/18 · 基礎知識 · 2 評論 · 併發執行緒池程序池

原文出處: ZiWenXie   

引言

Python標準庫為我們提供了threading和multiprocessing模組編寫相應的多執行緒/多程序程式碼,但是當專案達到一定的規模,頻繁建立/銷燬程序或者執行緒是非常消耗資源的,這個時候我們就要編寫自己的執行緒池/程序池,以空間換時間。但從Python3.2開始,標準庫為我們提供了concurrent.futures

模組,它提供了ThreadPoolExecutor和ProcessPoolExecutor兩個類,實現了對threading和multiprocessing的進一步抽象,對編寫執行緒池/程序池提供了直接的支援。

Executor和Future

concurrent.futures模組的基礎是Exectuor,Executor是一個抽象類,它不能被直接使用。但是它提供的兩個子類ThreadPoolExecutorProcessPoolExecutor卻是非常有用,顧名思義兩者分別被用來建立執行緒池和程序池的程式碼。我們可以將相應的tasks直接放入執行緒池/程序池,不需要維護Queue來操心死鎖的問題,執行緒池/程序池會自動幫我們排程。

Future這個概念相信有java和nodejs下程式設計經驗的朋友肯定不陌生了,你可以把它理解為一個在未來完成的操作,這是非同步程式設計的基礎,傳統程式設計模式下比如我們操作queue.get的時候,在等待返回結果之前會產生阻塞,cpu不能讓出來做其他事情,而Future的引入幫助我們在等待的這段時間可以完成其他的操作。關於在Python中進行非同步IO可以閱讀完本文之後參考我的Python併發程式設計之協程/非同步IO

p.s: 如果你依然在堅守Python2.x,請先安裝futures模組。

 

1

pip install futures

 

使用submit來操作執行緒池/程序池

我們先通過下面這段程式碼來了解一下執行緒池的概念

Python

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

# example1.py

from concurrent.futures import ThreadPoolExecutor

import time

def return_future_result(message):

    time.sleep(2)

    return message

pool = ThreadPoolExecutor(max_workers=2)  # 建立一個最大可容納2個task的執行緒池

future1 = pool.submit(return_future_result, ("hello"))  # 往執行緒池裡面加入一個task

future2 = pool.submit(return_future_result, ("world"))  # 往執行緒池裡面加入一個task

print(future1.done())  # 判斷task1是否結束

time.sleep(3)

print(future2.done())  # 判斷task2是否結束

print(future1.result())  # 檢視task1返回的結果

print(future2.result())  # 檢視task2返回的結果

我們根據執行結果來分析一下。我們使用submit方法來往執行緒池中加入一個task,submit返回一個Future物件,對於Future物件可以簡單地理解為一個在未來完成的操作。在第一個print語句中很明顯因為time.sleep(2)的原因我們的future1沒有完成,因為我們使用time.sleep(3)暫停了主執行緒,所以到第二個print語句的時候我們執行緒池裡的任務都已經全部結束。

 

1

2

3

4

5

6

7

8

9

10

ziwenxie :: ~ » python example1.py

False

True

hello

world

# 在上述程式執行的過程中,通過ps命令我們可以看到三個執行緒同時在後臺執行

ziwenxie :: ~ » ps -eLf | grep python

ziwenxie      8361  7557  8361  3    3 19:45 pts/0    00:00:00 python example1.py

ziwenxie      8361  7557  8362  0    3 19:45 pts/0    00:00:00 python example1.py

ziwenxie      8361  7557  8363  0    3 19:45 pts/0    00:00:00 python example1.py

 

上面的程式碼我們也可以改寫為程序池形式,api和執行緒池如出一轍,我就不羅嗦了。

Python

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

# example2.py

from concurrent.futures import ProcessPoolExecutor

import time

def return_future_result(message):

    time.sleep(2)

    return message

pool = ProcessPoolExecutor(max_workers=2)

future1 = pool.submit(return_future_result, ("hello"))

future2 = pool.submit(return_future_result, ("world"))

print(future1.done())

time.sleep(3)

print(future2.done())

print(future1.result())

print(future2.result())

下面是執行結果

 

1

2

3

4

5

6

7

8

9

10

11

ziwenxie :: ~ » python example2.py

False

True

hello

world

ziwenxie :: ~ » ps -eLf | grep python

ziwenxie      8560  7557  8560  3    3 19:53 pts/0    00:00:00 python example2.py

ziwenxie      8560  7557  8563  0    3 19:53 pts/0    00:00:00 python example2.py

ziwenxie      8560  7557  8564  0    3 19:53 pts/0    00:00:00 python example2.py

ziwenxie      8561  8560  8561  0    1 19:53 pts/0    00:00:00 python example2.py

ziwenxie      8562  8560  8562  0    1 19:53 pts/0    00:00:00 python example2.py

 

使用map/wait來操作執行緒池/程序池

除了submit,Exectuor還為我們提供了map方法,和內建的map用法類似,下面我們通過兩個例子來比較一下兩者的區別。

使用submit操作回顧

 

Python

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

# example3.py

import concurrent.futures

import urllib.request

URLS = ['http://httpbin.org', 'http://example.com/', 'https://api.github.com/']

def load_url(url, timeout):

    with urllib.request.urlopen(url, timeout=timeout) as conn:

        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly

with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:

    # Start the load operations and mark each future with its URL

    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}

    for future in concurrent.futures.as_completed(future_to_url):

        url = future_to_url[future]

        try:

            data = future.result()

        except Exception as exc:

            print('%r generated an exception: %s' % (url, exc))

        else:

            print('%r page is %d bytes' % (url, len(data)))

從執行結果可以看出,as_completed不是按照URLS列表元素的順序返回的

 

1

2

3

4

ziwenxie :: ~ » python example3.py

'http://example.com/' page is 1270 byte

'https://api.github.com/' page is 2039 bytes

'http://httpbin.org' page is 12150 bytes

 

使用map

 

Python

 

1

2

3

4

5

6

7

8

9

10

11

# example4.py

import concurrent.futures

import urllib.request

URLS = ['http://httpbin.org', 'http://example.com/', 'https://api.github.com/']

def load_url(url):

    with urllib.request.urlopen(url, timeout=60) as conn:

        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly

with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:

    for url, data in zip(URLS, executor.map(load_url, URLS)):

        print('%r page is %d bytes' % (url, len(data)))

從執行結果可以看出,map是按照URLS列表元素的順序返回的,並且寫出的程式碼更加簡潔直觀,我們可以根據具體的需求任選一種。

 

1

2

3

4

ziwenxie :: ~ » python example4.py

'http://httpbin.org' page is 12150 bytes

'http://example.com/' page is 1270 bytes

'https://api.github.com/' page is 2039 bytes

 

第三種選擇wait

wait方法接會返回一個tuple(元組),tuple中包含兩個set(集合),一個是completed(已完成的)另外一個是uncompleted(未完成的)。使用wait方法的一個優勢就是獲得更大的自由度,它接收三個引數FIRST_COMPLETED, FIRST_EXCEPTION 和ALL_COMPLETE,預設設定為ALL_COMPLETED。

我們通過下面這個例子來看一下三個引數的區別

Python

 

1

2

3

4

5

6

7

8

9

10

11

12

from concurrent.futures import ThreadPoolExecutor, wait, as_completed

from time import sleep

from random import randint

def return_after_random_secs(num):

    sleep(randint(1, 5))

    return "Return of {}".format(num)

pool = ThreadPoolExecutor(5)

futures = []

for x in range(5):

    futures.append(pool.submit(return_after_random_secs, x))

print(wait(futures))

# print(wait(futures, timeout=None, return_when='FIRST_COMPLETED'))

如果採用預設的ALL_COMPLETED,程式會阻塞直到執行緒池裡面的所有任務都完成。

 

1

2

3

4

5

6

7

ziwenxie :: ~ » python example5.py

DoneAndNotDoneFutures(done={

<Future at 0x7f0b06c9bc88 state=finished returned str>,

<Future at 0x7f0b06cbaa90 state=finished returned str>,

<Future at 0x7f0b06373898 state=finished returned str>,

<Future at 0x7f0b06352ba8 state=finished returned str>,

<Future at 0x7f0b06373b00 state=finished returned str>}, not_done=set())

如果採用FIRST_COMPLETED引數,程式並不會等到執行緒池裡面所有的任務都完成。

 

1

2

3

4

5

6

7

ziwenxie :: ~ » python example5.py

DoneAndNotDoneFutures(done={

<Future at 0x7f84109edb00 state=finished returned str>,

<Future at 0x7f840e2e9320 state=finished returned str>,

<Future at 0x7f840f25ccc0 state=finished returned str>},

not_done={<Future at 0x7f840e2e9ba8 state=running>,

<Future at 0x7f840e2e9940 state=running>})

 

思考題

寫一個小程式對比multiprocessing.pool(ThreadPool)和ProcessPollExecutor(ThreadPoolExecutor)在執行效率上的差距,結合上面提到的Future思考為什麼會造成這樣的結果。

References

DOCUMENTATION OF CONCURRENT-FUTURES