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
ohayoo
V2EX  ›  Python

小菜鸡请教 concurrent.futures.ThreadPoolExecutor 的问题

  •  
  •   ohayoo · 2023-02-07 19:39:05 +08:00 · 1902 次点击
    这是一个创建于 436 天前的主题,其中的信息可能已经有所发展或是发生改变。

    各位大佬,python 的 concurrent.futures.ThreadPoolExecutor 下的 map 返回值是按提交顺序来的吗?

    我之前一直以为用 map 的话 返回值是按提交的顺序来的,但今天看 map 对应的代码,注释是这样写的

    Returns: An iterator equivalent to: map(func, *iterables) but the calls may be evaluated out-of-order.

    这个意思是可能会乱序,并不能保证顺序返回吗?

    如果 map 不能保证顺序返回, 但多线程的时候又希望按顺序返回,该怎么办呢?还望大佬们赐教

    6 条回复    2023-02-20 13:42:07 +08:00
    echoless
        1
    echoless  
       2023-02-07 19:57:27 +08:00   ❤️ 1
    https://pymotw.com/3/concurrent.futures/

    map 会保证结果是 in order 的, 虽然 func 执行可能 out of order
    wuwukai007
        2
    wuwukai007  
       2023-02-07 19:57:36 +08:00   ❤️ 1
    jobs = [pool.submit(fn,i) for i in range(10)]
    [i.result() for i in jobs]
    ClericPy
        3
    ClericPy  
       2023-02-07 20:14:13 +08:00   ❤️ 1
    结果不乱, 执行乱
    julyclyde
        4
    julyclyde  
       2023-02-08 10:40:18 +08:00
    如果你希望按顺序返回
    那是你的需求有问题
    chr666
        5
    chr666  
       2023-02-20 13:34:17 +08:00
    传个 id 进去,最后返回时候排个序不就行了
    ohayoo
        6
    ohayoo  
    OP
       2023-02-20 13:42:07 +08:00
    @chr666 嗯嗯, 这个已经搞定了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5082 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 03:46 · PVG 11:46 · LAX 20:46 · JFK 23:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.