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

关于 ThreadPoolExecutor 的问题

  •  
  •   302766392 · 2018-07-27 10:56:18 +08:00 · 2109 次点击
    这是一个创建于 2072 天前的主题,其中的信息可能已经有所发展或是发生改变。
    Code:
    --------------------------------------------------------------
    import time
    from concurrent.futures import ThreadPoolExecutor

    def work_01(i):
    time.sleep(1)
    print(i)

    def work_02(i):
    time.sleep(2)
    print(i)

    def work_03(i):
    time.sleep(3)
    print(i)

    with ThreadPoolExecutor(max_workers=5) as executor:
    for i in range(2):
    executor.submit(work_01, i)
    executor.submit(work_02, i)
    executor.submit(work_03, i)

    print('over')
    -------------------------------------------------------------------

    return:
    -------------------------------------------------------------------
    0
    1
    0
    1
    0
    1
    over
    -------------------------------------------------------------------

    question:
    -------------------------------------------------------------------
    1. 在这里提问题怎么上传图片呀?
    2. executor.submit(work_01, i) executor.submit(work_02, i) executor.submit(work_03, i)
    这三个任务是需要依次顺序执行的,仅在三个任务顺序执行完再一次性打印结果,这有
    点类似于 mysql 的组合唯一值,同时我的线程池也是生效的,不会等待 3 个任务执行完再
    执行下 3 个任务
    3. 理想的展示效果如下:
    0
    0
    0
    1
    1
    1
    over



    1
    1
    1
    0
    0
    0
    over
    -------------------------------------------------------------------
    6 条回复    2018-07-28 08:53:07 +08:00
    shangfabao
        1
    shangfabao  
       2018-07-27 11:21:52 +08:00
    数量设置为 1,先后添加,然后监听所有线程执行完,java 是这么做的
    owenliang
        2
    owenliang  
       2018-07-27 12:00:54 +08:00
    了解一下互斥锁+条件变量,构造一个 future,每个线程执行完成后++完成次数,在主线程里 condition wait 等待 3 个都完成,则返回。
    whoami9894
        3
    whoami9894  
       2018-07-27 12:07:46 +08:00 via Android
    六个任务相当于同时开始,sleep(1)的两个最先执行完打印结果
    liuzhen
        4
    liuzhen  
       2018-07-27 15:25:09 +08:00
    给业务上要等待其他线程的所有线程维护一个 countdownlatch ?
    HackerOO7
        5
    HackerOO7  
       2018-07-27 16:05:52 +08:00
    线程同步,了解下
    lolizeppelin
        6
    lolizeppelin  
       2018-07-28 08:53:07 +08:00 via Android
    结果塞到队列里 不用加锁
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5622 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 436ms · UTC 06:33 · PVG 14:33 · LAX 23:33 · JFK 02:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.