Python 多線程/異步編程例子 | Multithread / asynchronous programming examples in Python

Python也是可以多線程/異步編程的。異步有什麼用呢?一個經典的思維模型如下:
一個程序需要到不同的服務器上去取數據,需要等各種數據收集齊了,才能繼續下一步。假如有10個服務器,如果是單前程,那麼只能發出一個請求,然後等待服務器返回,然後再發一下個請求。這樣每個時刻只有一個服務器在工作而其他9個都是閑置的。更高效的方法是同事向10個服務器發送請求,然後馬上拿到個「收據」,注意拿到收據只是說已經提交到服務器了,不代表已經完成請求。這個「收據」就叫future。請求全部提交完了,那麼主程序就可以等着全部服務器完成請求。

以下是個具體的例子,用Python 2.7實現

from concurrent.futures import ThreadPoolExecutor, as_completed

# assume this is a request to a server
def add(x, y):
    return x + y

executor = ThreadPoolExecutor(max_workers=10)
futures = []
for i in range(10):
    futures.append(executor.submit(add, i, i + 1))

for f in as_completed(futures):
    print(f.result())

Leave a Comment

Your email address will not be published.