如何在 Python 中使用執行緒實現併發?


簡介

Python 有不同的方法,例如使用執行緒、子程序、生成器和其他技巧來進行併發程式設計。在我們繼續實現執行緒之前,讓我們先了解一下併發到底是什麼。

併發是指在一個程式內部允許開啟許多不同的執行路徑,包括獨立的 I/O 流、執行 SQL 查詢等,使得執行看起來既是同時發生的又是相互獨立的。

如何操作..

首先,我們建立一個單執行緒來遍歷站點 URL,然後看看如何使用執行緒概念來加速程式。

# Step 1 - Make a list of website url you want to visit today
import requests

tutorialpoints_url = ['https://tutorialspoint.tw/python/index.htm',
'https://tutorialspoint.tw/cplusplus/index.htm',
'https://tutorialspoint.tw/java/index.htm',
'https://tutorialspoint.tw/html/index.htm',
'https://tutorialspoint.tw/cprogramming/index.htm']


# function to request the url passed and return the status code
def visit_site(site_url):
"""
Makes a GET request to a website URL and prints response information
"""
response = requests.get(site_url)
print(f' *** {site_url} returned {response.status_code} after {response.elapsed} seconds')


# Let us create a single thread to fetch the response
if __name__ == '__main__':
for site_url in tutorialpoints_url:
visit_site(site_url)
print(f" *** end of the program ***")


*** https://tutorialspoint.tw/python/index.htm returned 200 after 0:00:00.091103 seconds
*** https://tutorialspoint.tw/cplusplus/index.htm returned 200 after 0:00:00.069889 seconds
*** https://tutorialspoint.tw/java/index.htm returned 200 after 0:00:00.075864 seconds
*** https://tutorialspoint.tw/html/index.htm returned 200 after 0:00:00.075270 seconds
*** https://tutorialspoint.tw/cprogramming/index.htm returned 200 after 0:00:00.077984 seconds
*** end of the program ***

你從輸出中觀察到了什麼?站點 URL 是按順序處理的,想象一下,如果你有來自不同地理位置的數百個 URL 要訪問,那麼你的程式可能會花費大量時間等待伺服器響應。

現在讓我們編寫一個執行緒程式,以並行方式提交請求,並在不等待的情況下繼續執行下一步。

from threading import Thread

# function to request the url passed and return the status code
def visit_site(site_url):
"""
Makes a GET request to a website URL and prints response information
"""
response = requests.get(site_url)
print(f' *** {site_url} returned {response.status_code} after {response.elapsed} seconds')

# Loop through the website url and create threads for each url
if __name__ == '__main__':
for site_url in tutorialpoints_url:
t = Thread(target=visit_site, args=(site_url,))
t.start()


*** https://tutorialspoint.tw/python/index.htm returned 200 after 0:00:00.082176 seconds
*** https://tutorialspoint.tw/html/index.htm returned 200 after 0:00:00.086269 seconds
*** https://tutorialspoint.tw/java/index.htm returned 200 after 0:00:00.100746 seconds
*** https://tutorialspoint.tw/cplusplus/index.htm returned 200 after 0:00:00.120744 seconds *** https://tutorialspoint.tw/cprogramming/index.htm returned 200 after 0:00:00.111489 seconds

討論..

  • threading 庫可用於在自己的執行緒中執行任何 Python 可呼叫物件。

  • start() 方法使用 site_url 引數呼叫 visit_site 函式。

  • 執行緒一旦啟動,就會在自己的執行緒中執行,該執行緒完全由作業系統管理。

現在,如果你想檢視你的執行緒是處於活動狀態還是已結束(完成),可以使用 is_alive 函式。

if t.is_alive():
print(f' *** {t} is Still executing')
else:
print(f' *** {t} is Completed')


*** <Thread(Thread-10, stopped 4820)> is Completed

更新於: 2020-11-09

209 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告