Python 多线程 concurrent.futures

Python mulithreading concurrent.futures

我的问题是,每当我使用 thr.results() 时,程序的行为就像它在一个线程上的 运行ning 一样。但是当我不使用 thr.results() 时,它将使用 x 个线程 所以如果我删除我的 if 语句,它会在 10 个线程上 运行,如果我有它,它会像它在 1 个线程上一样运行

def search(query):
    r = requests.get("https://www.google.com/search?q=" + query)
    return r.status_code

pool = ThreadPoolExecutor(max_workers=10)
for i in range(50):
    thr = pool.submit(search, "stocks")
    print(i)
    if thr.result() != 404:
        print("Ran")

pool.shutdown(wait=True)

那是因为result会等待未来完成:

Return the value returned by the call. If the call hasn’t yet completed then this method will wait up to timeout seconds. If the call hasn’t completed in timeout seconds, then a concurrent.futures.TimeoutError will be raised. timeout can be an int or float. If timeout is not specified or None, there is no limit to the wait time.

当你在一个循环中有 result 时,你提交一个任务,然后等待它完成,然后再提交另一个任务,这样一次只能有一个任务 运行。

Update 您可以将返回的期货存储到列表中,并在提交所有任务后迭代它们。另一种选择是使用 map:

from concurrent.futures import ThreadPoolExecutor
import time

def square(x):
    time.sleep(0.3)
    return x * x

print(time.time())
with ThreadPoolExecutor(max_workers=3) as pool:
    for res in pool.map(square, range(10)):
        print(res)

print(time.time())

输出:

1485845609.983702
0
1
4
9
16
25
36
49
64
81
1485845611.1942203