代码之家  ›  专栏  ›  技术社区  ›  KiYugadgeter

为什么并发http请求的时间与顺序执行的时间相同?

  •  0
  • KiYugadgeter  · 技术社区  · 6 年前

    我学习了python3中的并发执行。
    我不知道为什么一个使用concurrent.futures.threadpoolexection,另一个不使用,但下面的http请求函数所用的时间是一样的。

    import urllib.request as ur
    import concurrent.futures
    
    def concurrent_exe(): # concurrent exection function that use ThreadPoolExecutor. 
        thread_pool_exe = concurrent.futures.ThreadPoolExecutor()
        for v in range(10000):
            future = thread_pool_exe.submit(access_example)
            print(v, future.result())
    
    def access_example():
        return ur.urlopen("http://example.com").read().decode("utf-8")[10:15]
    
    def seq_exe(): # sequential exectute function
        for v in range(10000):
            print(v, access_example())
    

    我不知道为什么这些功能几乎需要同样的时间。

    我的环境是:

    • Python 3.6

    • 虚拟机上的ubuntu 18.10(主机操作系统:windows1803)

    1 回复  |  直到 6 年前
        1
  •  0
  •   KiYugadgeter    6 年前

    我知道我应该在代码中更改什么。 结果是阻塞法。所以应该等到第一个未来完成。

    def concurrent_exe():
        futures_list = []
        thread_pool_exe = concurrent.futures.ThreadPoolExecutor()
        for v in range(10000):
            future = thread_pool_exe.submit(access_example, v)
            futures_list.append(future)
        for v in concurrent.futures.as_completed(futures_list):
            print(v.result())