V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2020-07-22 14:34:30 +08:00 · 1479 次点击
    这是一个创建于 1366 天前的主题,其中的信息可能已经有所发展或是发生改变。

    先上代码

    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 条回复    2020-07-22 16:28:09 +08:00
    xiaolinjia
        1
    xiaolinjia  
       2020-07-22 15:08:16 +08:00
    def func3():
    import threading
    t = threading.Thread(target=func2)
    t.start()
    return 1
    ToughGuy
        2
    ToughGuy  
       2020-07-22 16:28:09 +08:00
    直接把 futures return 回去

    def func2():
    ----....
    ----returun exe.map(func1,range(10))
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1355 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 23:42 · PVG 07:42 · LAX 16:42 · JFK 19:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.