您需要使用为此,最简单的方法是通过multiprocessing.pool.ThreadPool
包(不要让它欺骗你,尽管它处于包中但不是多处理):
import requests
from multiprocessing.pool import ThreadPool
# let's make it a bit more flexible
RANDOM_URL = 'https://www.random.org/integers/'
RANDOM_PARAMS = {"num": 1, "min": 0, "max": 10, "col": 1, "base": 10,
"format": "plain", "rnd": "new"}
def func1(*args): # args added to account for the dummy payload from pool.map
return int(requests.get(RANDOM_URL, params=RANDOM_PARAMS).text)
pool = ThreadPool(processes=3)
response_sum = sum(pool.map(func1, range(3)))
print("Squared response: {}".format(response_sum**2))
为什么不能线程? –
如果你使用的是Python 3,你可以使用它的异步特性...在Python 2中,你必须用[threading]来做(https://docs.python.org/2/library/threading.html) –