推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Hiyokunotori
V2EX  ›  Python

请问 Python 中的 ThreadPoolExecutor 嵌套使用时外层如何能不等待内层结果并直接返回

  •  
  •   Hiyokunotori · Jul 22, 2020 · 2376 views
    This topic created in 2145 days ago, the information mentioned may be changed or developed.

    先上代码

    from concurrent.futures import ThreadPoolExecutor
    import time
    from loguru import logger
    
    def func1(x):
        time.sleep(2)
        return x
    
    def func2():
        my = []
        exe = ThreadPoolExecutor()
        for r in exe.map(func1,range(10)):
            my.append(r)
        exe.shutdown()
        logger.info(my)
    
    def func3():
        exe = ThreadPoolExecutor(1)
        exe.submit(func2)
        # 这里我想先返回 1,然后异步执行函数 haha2,但是我如果设置了 wait 为 False 的话 haha2 就不会执行,
        # 不设置的话得等到 haha2 执行完毕才能返回 1,我该怎么做
        exe.shutdown(wait=False)
        return 1
    
    if __name__ == '__main__':
        res = func3()
        print(res)
    

    我现在的需求是有三个函数,函数 2 中会使用 ThreadPoolExecutor 去执行函数 1(为了提升效率),函数 3 中会执行函数 2 并返回一个值,但是我想函数 3 先返回值就给一个 ThreadPoolExecutor(1)并且设置 wait 为 False,但是这样函数 2 并没有执行,请问我该如何实现我得目的。。。还是说 ThreadPoolExecutor 不适用这种场景,那么我应该怎么办呢

    2 replies    2020-07-22 16:28:09 +08:00
    xiaolinjia
        1
    xiaolinjia  
       Jul 22, 2020
    def func3():
    import threading
    t = threading.Thread(target=func2)
    t.start()
    return 1
    ToughGuy
        2
    ToughGuy  
       Jul 22, 2020
    直接把 futures return 回去

    def func2():
    ----....
    ----returun exe.map(func1,range(10))
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   895 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 20:05 · PVG 04:05 · LAX 13:05 · JFK 16:05
    ♥ Do have faith in what you're doing.