最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python并發(fā)編程多進程,多線程及GIL全局解釋器鎖

 更新時間:2022年07月19日 08:54:10   作者:企鵝與蟒蛇  
這篇文章主要介紹了Python并發(fā)編程多進程,多線程及GIL全局解釋器鎖,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下

1. 并發(fā)與并行

  • 所謂的并行(Parallelism),就是多個彼此獨立的任務可以同時一起執(zhí)行,彼此并不相互干擾,并行強調(diào)的是同時且獨立的運行,彼此不需要協(xié)作。
  • 而所謂并發(fā)(Concurrency),則是多個任務彼此交替執(zhí)行,但是同一時間只能有一個處于運行狀態(tài),并發(fā)執(zhí)行強調(diào)任務之間的彼此協(xié)作。

并發(fā)通常被誤解為并行,并發(fā)實際是隱式的調(diào)度獨立的代碼,以協(xié)作的方式運行。比如在等待IO線程完成IO操作之前,可以啟動IO線程之外的其他獨立代碼同步執(zhí)行其他操作。

關(guān)于并發(fā)、并行的圖示,如下:

由于CPython解釋器中的全局解釋器鎖(GIL,Global Interpreter Lock)的存在,所以Python中的并行實際上是一種假并行,并不是真正意義上的同時獨立運行。

2. 線程與進程的應用場景

進程(Process)是操作系統(tǒng)層面的一個抽象概念,它是運行代碼創(chuàng)建出來的、加載到內(nèi)存中運行的程序。電腦上通常運行著多個進程,這些進程之間是彼此獨立運行的。

線程(Thread)是操作系統(tǒng)可以調(diào)度的最小運行程序單位,其包含在進程中,一個進程中通常至少包含1個線程,一些進程中會包含多個線程。多個線程運行的都是父進程的相同代碼,理想情況下,這些線程是并行執(zhí)行的,但由于GIL的存在,所以它們實際上是交替執(zhí)行的,并不是真正意義上的獨立、并行的執(zhí)行的。

下表是進程與線程的對比:

對于IO密集型的操作,更適合使用多線程編程的方式來解決問題;對于CPU密集型的操作,則更適合使用多進程編程的方式來解決問題。

2.1. 并行/并發(fā)編程相關(guān)的技術(shù)棧

Python中提供了一些模塊用于實現(xiàn)并行/并發(fā)編程,具體如下所示:

threading:Python中進行多線程編程的標準庫,是一個對_thread進行再封裝的高級模塊。multiprocessing:類似于threading模塊,提供的API接口也與threading模塊類似,不同的是它進行多進程編程。concurrent.futures:標準庫中的一個模塊,在線程編程模塊的基礎(chǔ)上抽象出來的更高級實現(xiàn),且該模塊的編程為異步模式。queue:任務隊列模塊,queue中提供的隊列是線程安全的,所以可以使用這個模塊進行線程之間進行安全的數(shù)據(jù)交換操作。不支持分布式。celery:一個高級的分布式任務隊列,通過multiprocessing模塊或者gevent模塊可以實現(xiàn)隊列中人物的并發(fā)執(zhí)行。支持多節(jié)點之間的分布式計算。 2.2. 通過編碼比較多進程與多線程的執(zhí)行效果

在下面的代碼中,定義了兩個函數(shù):only_sleep()以及crunch_numbers(),前者用于模擬IO密集型操作(需要頻繁中斷),后者用于模擬CPU密集型操作。

然后在串行調(diào)用、多線程的方式調(diào)用、多進程的方式調(diào)用,三種不同的執(zhí)行環(huán)境中,比較各個函數(shù)的執(zhí)行效率情況。

具體代碼以及執(zhí)行結(jié)果如下所示:

import time
import datetime
import logging
import threading
import multiprocessing

FORMAT = "%(asctime)s [%(processName)s %(process)d] %(threadName)s %(thread)d <=%(message)s=>"
logging.basicConfig(format=FORMAT, level=logging.INFO, datefmt='%H:%M:%S')
def only_sleep():
	"""
	模擬IO阻塞型操作,此時多線程優(yōu)勢明顯

	:return:
	"""
	logging.info('in only_sleep function')
	time.sleep(1)
def crunch_numbers():
	"""
	模擬CPU密集型操作,此時多進程優(yōu)勢明顯
	:return:
	"""
	logging.info('in crunch_numbers function')
	x = 0
	while x < 1000000:
    	x += 1
if __name__ == '__main__':
	work_repeat = 4
	print('==>> only_sleep function test')
	count = 0
	for func in (only_sleep, crunch_numbers):
    	count += 1
	    # run tasks serially
    	start1 = datetime.datetime.now()
	    for i in range(work_repeat):
    	    func()
	    stop1 = datetime.datetime.now()
    	delta1 = (stop1 - start1).total_seconds()
	    print('Serial Execution takes {} seconds~'.format(delta1))

    	# run tasks with multi-threads
	    start2 = datetime.datetime.now()
    	thread_lst = [threading.Thread(target=func, name='thread-worker' + str(i)) for i in range(work_repeat)]
	    [thd.start() for thd in thread_lst]
    	[thd.join() for thd in thread_lst]
	    stop2 = datetime.datetime.now()
    	delta2 = (stop2 - start2).total_seconds()
	    print('Multi-Threads takes {} seconds~'.format(delta2))
    	# run tasks with multiprocessing
	    start3 = datetime.datetime.now()
    	proc_lst = [multiprocessing.Process(target=func, name='process-worker' + str(i)) for i in range(work_repeat)]
	    [thd.start() for thd in proc_lst]
    	[thd.join() for thd in proc_lst]
	    stop3 = datetime.datetime.now()
    	delta3 = (stop3 - start3).total_seconds()
	    print('Multi-Processing takes {} seconds~'.format(delta3))
    	if count == 1:
        	print('\n', '*.' * 30, end='\n\n')
	        print('==>> crunch_numbers function test')

上述代碼的執(zhí)行結(jié)果如下:

23:55:51 [MainProcess 568124] MainThread 182168 <=in only_sleep function=>
==>> only_sleep function test
23:55:52 [MainProcess 568124] MainThread 182168 <=in only_sleep function=>
23:55:53 [MainProcess 568124] MainThread 182168 <=in only_sleep function=>
23:55:54 [MainProcess 568124] MainThread 182168 <=in only_sleep function=>
23:55:55 [MainProcess 568124] thread-worker0 553012 <=in only_sleep function=>
23:55:55 [MainProcess 568124] thread-worker1 567212 <=in only_sleep function=>
23:55:55 [MainProcess 568124] thread-worker2 547252 <=in only_sleep function=>
23:55:55 [MainProcess 568124] thread-worker3 561892 <=in only_sleep function=>
Serial Execution takes 4.022761 seconds~
Multi-Threads takes 1.01416 seconds~
23:55:56 [process-worker0 563068] MainThread 567480 <=in only_sleep function=>
23:55:56 [process-worker1 567080] MainThread 567628 <=in only_sleep function=>
23:55:56 [process-worker2 567868] MainThread 563656 <=in only_sleep function=>
23:55:56 [process-worker3 567444] MainThread 566436 <=in only_sleep function=>
23:55:57 [MainProcess 568124] MainThread 182168 <=in crunch_numbers function=>
Multi-Processing takes 1.11466 seconds~

*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.*.

==>> crunch_numbers function test
23:55:57 [MainProcess 568124] MainThread 182168 <=in crunch_numbers function=>
23:55:57 [MainProcess 568124] MainThread 182168 <=in crunch_numbers function=>
23:55:57 [MainProcess 568124] MainThread 182168 <=in crunch_numbers function=>
Serial Execution takes 0.1786 seconds~
23:55:57 [MainProcess 568124] thread-worker0 567412 <=in crunch_numbers function=>
23:55:57 [MainProcess 568124] thread-worker1 566468 <=in crunch_numbers function=>
23:55:57 [MainProcess 568124] thread-worker2 565272 <=in crunch_numbers function=>
23:55:57 [MainProcess 568124] thread-worker3 568044 <=in crunch_numbers function=>
Multi-Threads takes 0.195057 seconds~
23:55:58 [process-worker0 567652] MainThread 561892 <=in crunch_numbers function=>
23:55:58 [process-worker1 553012] MainThread 547252 <=in crunch_numbers function=>
23:55:58 [process-worker2 554024] MainThread 556500 <=in crunch_numbers function=>
23:55:58 [process-worker3 565004] MainThread 566108 <=in crunch_numbers function=>
Multi-Processing takes 0.155246 seconds~

Process finished with exit code 0

從上述執(zhí)行結(jié)果中可以看出:

上述代碼的執(zhí)行結(jié)果也驗證了此前的結(jié)論:對于IO密集型操作,適合使用多線程編程的方式解決問題;而對于CPU密集型的操作,則適合使用多進程編程的方式解決問題。

3. Python中的GIL是什么,它影響什么

GIL是CPython中實現(xiàn)的全局解釋器鎖 (Global Interpreter Lock),由于CPython是使用最廣泛的Python解釋器,所以GIL也是Python世界中最飽受爭議的一個主題。

GIL是互斥鎖,其目的是為了確保線程安全,正是因為有了GIL,所以可以很方便的與外部非線程安全的模塊或者庫結(jié)合起來。但是這也是有代價的,由于有了GIL,所以導致Python中的并行并不是真正意義上的并行,所以也就無法同時創(chuàng)建兩個使用相同代碼段的線程,相同代碼的線程只能有一個處于執(zhí)行狀態(tài)。因為GIL互斥鎖,相同代碼訪問的數(shù)據(jù)會被加鎖,只有當一個線程釋放鎖之后,相同代碼的另一個線程才能訪問未被加鎖的數(shù)據(jù)。

所以Python中的多線程是相互交替執(zhí)行的,并不是真正的并行執(zhí)行的。但是在CPython之外的一些庫,是可以實現(xiàn)真正意義上的并行的,比如numpy這個數(shù)據(jù)處理常用的庫。

到此這篇關(guān)于Python并發(fā)編程多進程,多線程及GIL全局解釋器鎖的文章就介紹到這了,更多相關(guān)Python GIL解釋器鎖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

巴林左旗| 永仁县| 汶川县| 泸溪县| 昌黎县| 金山区| 吉木萨尔县| 天祝| 衡水市| 福州市| 富顺县| 泾阳县| 勐海县| 连州市| 西和县| 黔西县| 隆子县| 青阳县| 富川| 铁力市| 临洮县| 枣庄市| 余姚市| 安顺市| 安达市| 大竹县| 黄梅县| 高青县| 平利县| 西丰县| 洛扎县| 武义县| 岳池县| 香格里拉县| 大方县| 和政县| 乌拉特后旗| 深圳市| 贵港市| 安龙县| 象州县|