使用Python進行並發編程

來源:互聯網
上載者:User
讓電腦程式並發的運行是一個經常被討論的話題,今天我想討論一下Python下的各種並發方式。

並發方式

線程(Thread)

多線程幾乎是每一個程式猿在使用每一種語言時都會首先想到用於解決並發的工具(JS程式員請迴避),使用多線程可以有效利用CPU資源(Python例外)。然而多線程所帶來的程式的複雜度也不可避免,尤其是對競爭資源的同步問題。

然而在python中由於使用了全域解釋鎖(GIL)的原因,代碼並不能同時在多核上並發的運行,也就是說,Python的多線程不能並發,很多人會發現使用多線程來改進自己的Python代碼後,程式的運行效率卻下降了,這是多麼蛋疼的一件事呀!如果想瞭解更多細節,推薦閱讀這篇文章。實際上使用多線程的編程模型是很困難的,程式員很容易犯錯,這並不是程式員的錯誤,因為並行思維是反人類的,我們大多數人的思維是串列(精神分裂不討論),而且馮諾依曼設計的電腦架構也是以順序執行為基礎的。所以如果你總是不能把你的多線程程式搞定,恭喜你,你是個思維正常的程式猿:)

Python提供兩組線程的介面,一組是thread模組,提供基礎的,低等級(Low Level)介面,使用Function作為線程的運行體。還有一組是threading模組,提供更容易使用的基於對象的介面(類似於java),可以繼承Thread對象來實現線程,還提供了其它一些線程相關的對象,例如Timer,Lock

使用thread模組的例子

1

2

3

4

5

import thread

def worker():

"""thread worker function"""

PRint 'Worker'

thread.start_new_thread(worker)

使用threading模組的例子

1

2

3

4

5

6

import threading

def worker():

"""thread worker function"""

print 'Worker'

t = threading.Thread(target=worker)

t.start()

或者Java Style

1

2

3

4

5

6

7

8

9

10

import threading

class worker(threading.Thread):

def __init__(self):

pass

def run():

"""thread worker function"""

print 'Worker'

t = worker()

t.start()

進程 (Process)

由於前文提到的全域解釋鎖的問題,Python下比較好的並行方式是使用多進程,這樣可以非常有效使用CPU資源,並實現真正意義上的並發。當然,進程的開銷比線程要大,也就是說如果你要建立數量驚人的並發進程的話,需要考慮一下你的機器是不是有一顆強大的心。

Python的mutliprocess模組和threading具有類似的介面。

1

2

3

4

5

6

7

8

from multiprocessing import Process

def worker():

"""thread worker function"""

print 'Worker'

p = Process(target=worker)

p.start()

p.join()

由於線程共用相同的地址空間和記憶體,所以線程之間的通訊是非常容易的,然而進程之間的通訊就要複雜一些了。常見的處理序間通訊有,管道,訊息佇列,Socket介面(TCP/IP)等等。

Python的mutliprocess模組提供了封裝好的管道和隊列,可以方便的在進程間傳遞訊息。

Python進程間的同步使用鎖,這一點喝線程是一樣的。

另外,Python還提供了進程池Pool對象,可以方便的管理和控制線程。

遠程分布式主機 (Distributed Node)

隨著大資料時代的到臨,摩爾定理在單機上似乎已經失去了效果,資料的計算和處理需要分布式的電腦網路來運行,程式並行的運行在多個主機節點上,已經是現在的軟體架構所必需考慮的問題。

遠程主機間的處理序間通訊有幾種常見的方式

TCP/IP

TCP/IP是所有遠程通訊的基礎,然而API比較低層級,使用起來比較繁瑣,所以一般不會考慮

遠程方法調用 Remote Function Call

RPC是早期的遠程處理序間通訊的手段。Python下有一個開源的實現RPyC

遠程對象 Remote Object

遠程對象是更進階別的封裝,程式可以想操作本機物件一樣去操作一個遠程對象在本地的代理。遠程對象最廣為使用的規範CORBA,CORBA最大的好處是可以在不同語言和平台中進行通訊。當讓不用的語言和平台還有一些各自的遠程對象實現,例如Java的RMI,MS的DCOM

Python的開源實現,有許多對遠程對象的支援

Dopy

Fnorb (CORBA)

ICE

omniORB (CORBA)

Pyro

YAMI

訊息佇列 Message Queue

比起RPC或者遠程對象,訊息是一種更為靈活的通訊手段,常見的支援Python介面的訊息機制有

RabbitMQ

ZeroMQ

Kafka

AWS SQS + BOTO

在遠程主機上執行並發和本地的多進程並沒有非常大的差異,都需要解決處理序間通訊的問題。當然對遠程進程的管理和協調比起本地要複雜。

Python下有許多開源的架構來支援分布式的並發,提供有效管理手段包括:

Celery

Celery是一個非常成熟的Python分布式架構,可以在分布式的系統中,非同步執行任務,並提供有效管理和調度功能。參考這裡

SCOOP

SCOOP (Scalable COncurrent Operations in Python)提供簡單易用的分布式調用介面,使用Future介面來進行並發。

Dispy

相比起Celery和SCOOP,Dispy提供更為輕量級的分布式並行服務

PP

PP (Parallel Python)是另外一個輕量級的Python並行服務, 參考這裡

Asyncoro

Asyncoro是另一個利用Generator實現分布式並發的Python架構,

當然還有許多其它的系統,我沒有一一列出

另外,許多的分布式系統多提供了對Python介面的支援,例如Spark

偽線程 (Pseudo-Thread)

還有一種並發手段並不常見,我們可以稱之為偽線程,就是看上去像是線程,使用的介面類似線程介面,但是實際使用非線程的方式,對應的線程開銷也不存的。

greenlet

greenlet提供輕量級的coroutines來支援進程內的並發。

greenlet是Stackless的一個副產品,使用tasklet來支援一中被稱之為微線程(mirco-thread)的技術,這裡是一個使用greenlet的偽線程的例子

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

from greenlet import greenlet

def test1():

print 12

gr2.switch()

print 34

def test2():

print 56

gr1.switch()

print 78

gr1 = greenlet(test1)

gr2 = greenlet(test2)

gr1.switch()

運行以上程式得到如下結果:

1

2

3

12

56

34

偽線程gr1 switch會列印12,然後調用gr2 switch得到56,然後switch回到gr1,列印34,然後偽線程gr1結束,程式退出,所以78永遠不會被列印。通過這個例子我們可以看出,使用偽線程,我們可以有效控製程序的執行流程,但是偽線程並不存在真正意義上的並發。

eventlet,gevent和concurence都是基於greenlet提供並發的。

eventlet http://eventlet.net/

eventlet是一個提供網路調用並發的Python庫,使用者可以以非阻塞的方式來調用阻塞的IO操作。

1

2

3

4

5

6

7

8

9

10

11

12

import eventlet

from eventlet.green import urllib2

urls = ['http://www.google.com', 'http://www.example.com', 'http://www.python.org']

def fetch(url):

return urllib2.urlopen(url).read()

pool = eventlet.GreenPool()

for body in pool.imap(fetch, urls):

print("got body", len(body))

執行結果如下

1

2

3

('got body', 17629)

('got body', 1270)

('got body', 46949)

eventlet為了支援generator的操作對urllib2做了修改,介面和urllib2是一致的。這裡的GreenPool和Python的Pool介面一致。

gevent

gevent和eventlet類似,關於它們的差異大家可以參考這篇文章

1

2

3

4

5

6

7

import gevent

from gevent import socket

urls = ['www.google.com', 'www.example.com', 'www.python.org']

jobs = [gevent.spawn(socket.gethostbyname, url) for url in urls]

gevent.joinall(jobs, timeout=2)

print [job.value for job in jobs]

執行結果如下:

1

['206.169.145.226', '93.184.216.34', '23.235.39.223']

concurence https://github.com/concurrence/concurrence

concurence是另外一個利用greenlet提供網路並發的開源庫,我沒有用過,大家可以自己嘗試一下。

實戰運用

通常需要用到並發的場合有兩種,一種是計算密集型,也就是說你的程式需要大量的CPU資源;另一種是IO密集型,程式可能有大量的讀寫操作,包括讀寫檔案,收髮網絡請求等等。

計算密集型

對應計算密集型的應用,我們選用著名的蒙特卡洛演算法來計算PI值。基本原理如下

蒙特卡洛演算法利用統計學原理來類比計算圓周率,在一個正方形中,一個隨機的點落在1/4圓的地區(紅色點)的機率與其面積成正比。也就該機率 p = Pi * R*R /4 : R* R , 其中R是正方形的邊長,圓的半徑。也就是說該機率是圓周率的1/4, 利用這個結論,只要我們類比出點落在四分之一圓上的機率就可以知道圓周率了,為了得到這個機率,我們可以通過大量的實驗,也就是產生大量的點,看看這個點在哪個地區,然後統計出結果。

基本演算法如下:

1

2

3

4

5

from math import hypot

from random import random

def test(tries):

return sum(hypot(random(), random()) < 1 for _ in range(tries))

這裡test方法做了n(tries)次實驗,返回落在四分之一圓中的點的個數。判斷方法是檢查該點到圓心的距離,如果小於R則是在圓上。

通過大量的並發,我們可以快速的運行多次實驗,實驗的次數越多,結果越接近真實的圓周率。

這裡給出不同並發方法的程式碼

非並發

我們先在單線程,但進程運行,看看效能如何

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

from math import hypot

from random import random

import eventlet

import time

def test(tries):

return sum(hypot(random(), random()) < 1 for _ in range(tries))

def calcPi(nbFutures, tries):

ts = time.time()

result = map(test, [tries] * nbFutures)

ret = 4. * sum(result) / float(nbFutures * tries)

span = time.time() - ts

print "time spend ", span

return ret

print calcPi(3000,4000)

多線程 thread

為了使用線程池,我們用multiprocessing的dummy包,它是對多線程的一個封裝。注意這裡代碼雖然一個字的沒有提到線程,但它千真萬確是多線程。

通過測試我們開(jing)心(ya)的發現,果然不出所料,當線程池為1是,它的運行結果和沒有並發時一樣,當我們把線程池數字設定為5時,耗時幾乎是沒有並發的2倍,我的測試資料從5秒到9秒。所以對於計算密集型的任務,還是放棄多線程吧。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

from multiprocessing.dummy import Pool

from math import hypot

from random import random

import time

def test(tries):

return sum(hypot(random(), random()) < 1 for _ in range(tries))

def calcPi(nbFutures, tries):

ts = time.time()

p = Pool(1)

result = p.map(test, [tries] * nbFutures)

ret = 4. * sum(result) / float(nbFutures * tries)

span = time.time() - ts

print "time spend ", span

return ret

if __name__ == '__main__':

p = Pool()

print("pi = {}".format(calcPi(3000, 4000)))

多進程 multiprocess

理論上對於計算密集型的任務,使用多進程並發比較合適,在以下的例子中,進程池的規模設定為5,修改進程池的大小可以看到對結果的影響,當進程池設定為1時,和多線程的結果所需的時間類似,因為這時候並不存在並發;當設定為2時,回應時間有了明顯的改進,是之前沒有並發的一半;然而繼續擴大進程池對效能影響並不大,甚至有所下降,也許我的Apple Air的CPU只有兩個核?

當心,如果你設定一個非常大的進程池,你會遇到 Resource temporarily unavailable的錯誤,系統並不能支援建立太多的進程,畢竟資源是有限的。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

from multiprocessing import Pool

from math import hypot

from random import random

import time

def test(tries):

return sum(hypot(random(), random()) < 1 for _ in range(tries))

def calcPi(nbFutures, tries):

ts = time.time()

p = Pool(5)

result = p.map(test, [tries] * nbFutures)

ret = 4. * sum(result) / float(nbFutures * tries)

span = time.time() - ts

print "time spend ", span

return ret

if __name__ == '__main__':

print("pi = {}".format(calcPi(3000, 4000)))

gevent (偽線程)

不論是gevent還是eventlet,因為不存在實際的並發,回應時間和沒有並發區別不大,這個和測試結果一致。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

import gevent

from math import hypot

from random import random

import time

def test(tries):

return sum(hypot(random(), random()) < 1 for _ in range(tries))

def calcPi(nbFutures, tries):

ts = time.time()

jobs = [gevent.spawn(test, t) for t in [tries] * nbFutures]

gevent.joinall(jobs, timeout=2)

ret = 4. * sum([job.value for job in jobs]) / float(nbFutures * tries)

span = time.time() - ts

print "time spend ", span

return ret

print calcPi(3000,4000)

eventlet (偽線程)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

from math import hypot

from random import random

import eventlet

import time

def test(tries):

return sum(hypot(random(), random()) < 1 for _ in range(tries))

def calcPi(nbFutures, tries):

ts = time.time()

pool = eventlet.GreenPool()

result = pool.imap(test, [tries] * nbFutures)

ret = 4. * sum(result) / float(nbFutures * tries)

span = time.time() - ts

print "time spend ", span

return ret

print calcPi(3000,4000)

SCOOP

SCOOP中的Future介面符合PEP-3148的定義,也就是在Python3中提供的Future介面。

在預設的SCOOP配置環境下(單機,4個Worker),並發的效能有提高,但是不如兩個進程池配置的多進程。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

from math import hypot

from random import random

from scoop import futures

import time

def test(tries):

return sum(hypot(random(), random()) < 1 for _ in range(tries))

def calcPi(nbFutures, tries):

ts = time.time()

expr = futures.map(test, [tries] * nbFutures)

ret = 4. * sum(expr) / float(nbFutures * tries)

span = time.time() - ts

print "time spend ", span

return ret

if __name__ == "__main__":

print("pi = {}".format(calcPi(3000, 4000)))

Celery

任務代碼

1

2

3

4

5

6

7

8

9

10

11

from celery import Celery

from math import hypot

from random import random

app = Celery('tasks', backend='amqp', broker='amqp://guest@localhost//')

app.conf.CELERY_RESULT_BACKEND = 'db+sqlite:///results.sqlite'

@app.task

def test(tries):

return sum(hypot(random(), random()) < 1 for _ in range(tries))

用戶端代碼

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

from celery import group

from tasks import test

import time

def calcPi(nbFutures, tries):

ts = time.time()

result = group(test.s(tries) for i in xrange(nbFutures))().get()

ret = 4. * sum(result) / float(nbFutures * tries)

span = time.time() - ts

print "time spend ", span

return ret

print calcPi(3000, 4000)

使用Celery做並發的測試結果出乎意料(環境是單機,4frefork的並發,訊息broker是rabbitMQ),是所有測試案例裡最糟糕的,回應時間是沒有並發的5~6倍。這也許是因為控制協調的開銷太大。對於這樣的計算任務,Celery也許不是一個好的選擇。

asyncoro

Asyncoro的測試結果和非並發保持一致。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

import asyncoro

from math import hypot

from random import random

import time

def test(tries):

yield sum(hypot(random(), random()) < 1 for _ in range(tries))

def calcPi(nbFutures, tries):

ts = time.time()

coros = [ asyncoro.Coro(test,t) for t in [tries] * nbFutures]

ret = 4. * sum([job.value() for job in coros]) / float(nbFutures * tries)

span = time.time() - ts

print "time spend ", span

return ret

print calcPi(3000,4000)

IO密集型

IO密集型的任務是另一種常見的用例,例如網路WEB伺服器就是一個例子,每秒鐘能處理多少個請求時WEB伺服器的重要指標。

我們就以網頁讀取作為最簡單的例子

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

from math import hypot

import time

import urllib2

urls = ['http://www.google.com', 'http://www.example.com', 'http://www.python.org']

def test(url):

return urllib2.urlopen(url).read()

def testIO(nbFutures):

ts = time.time()

map(test, urls * nbFutures)

span = time.time() - ts

print "time spend ", span

testIO(10)

在不同並發庫下的代碼,由於比較類似,我就不一一列出。大家可以參考計算密集型中代碼做參考。

通過測試我們可以發現,對於IO密集型的任務,使用多線程,或者是多進程都可以有效提高程式的效率,而使用偽線程效能提升非常顯著,eventlet比沒有並發的情況下,回應時間從9秒提高到0.03秒。同時eventlet/gevent提供了非阻塞的非同步呼叫模式,非常方便。這裡推薦使用線程或者偽線程,因為在回應時間類似的情況下,線程和偽線程消耗的資源更少。

總結

Python提供了不同的並發方式,對應於不同的情境,我們需要選擇不同的方式進行並發。選擇合適的方式,不但要對該方法的原理有所瞭解,還應該做一些測試和實驗,資料才是你做選擇的最好參考。

以上就是使用Python進行並發編程的內容,更多相關文章請關注topic.alibabacloud.com(www.php.cn)!

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.