我的问题是,每当我使用thr.results()时,程序就像在一个线程上运行一样。但是当我不使用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)发布于 2017-01-31 06:26:10
这是因为result将等待未来的完成:
返回调用返回的值。如果调用尚未完成,则此方法将等待到超时秒。如果调用在超时秒内未完成,则将引发concurrent.futures.TimeoutError。超时可以是int或float。如果未指定超时或无超时,则等待时间没有限制。
当循环中有result时,提交一个任务,然后等待它完成,然后提交另一个任务,以便一次只能运行一个任务。
更新您可以将返回的期货存储到列表中,并在提交所有任务后对它们进行迭代。其他选项是使用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.1942203https://stackoverflow.com/questions/41950894
复制相似问题