with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool:
results = pool.map(post, words)
concurrent.futures.wait(results)
如果您愿意,您可以编写自己的线程,只给每个线程 1/10 的 words 并让它循环调用 post:
def posts(words):
for word in words:
post(word)
groupsize = len(words)/10
t = [threading.Thread(target=posts, args=[words[i*groupsize:(i+1)*groupsize]]
for i in range(10)]
for thread in t:
thread.start()
for thread in t:
thread.join()
无论哪种方式,显然我只是凭空得出数字 10(因为它比大多数浏览器或 Web 服务客户端允许您创建的最大同时连接数多一点),但您需要做一些性能进行测试以找到最佳值(value)。
与此同时,如果实际读取是在浪费时间,而您实际上并不需要响应,而且它们相当大,并且您不想测试服务器发送真实响应的能力,您可能需要一旦您知道您将获得正确的数据,请立即关闭套接字。您可以通过编写自己的处理程序来使用 urllib2 来完成此操作,但这听起来工作量很大。我认为在这种情况下,只下降到套接字级别实际上会更简单。首先,记录为每个 POST 发送的请求,以及当一切正常时您返回的预期 200 行。然后做这样的事情:
with closing(socket.socket()) as c:
c.connect(('127.0.0.1', 8000))
c.send(REQUEST_STRING_FORMAT.format([word]))
with c.makefile() as f:
response = f.readline()
if response != RESPONSE_200_STRING:
response += f.read()
with open('error.html','w') as k:
k.write(response)