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

如何实现分批执行线程

  •  
  •   Arabot9 · 2020-03-20 22:36:04 +08:00 · 2593 次点击
    这是一个创建于 1496 天前的主题,其中的信息可能已经有所发展或是发生改变。

    预先设定好线程池容量为 50,

    1、如何实现 10 个线程为一组执行,执行完这一组继续执行下一组十个线程?

    2、如何实现设定最大同时任务数为 10 个线程,当中有线程结束后,剩下未执行的线程替补进来?

    感谢解答!

    7 条回复    2020-03-21 10:13:00 +08:00
    Juszoe
        1
    Juszoe  
       2020-03-20 23:04:54 +08:00
    1. 每次启动十个线程,用 join 等待线程全部完成,再创建十个
    2. 这不就是线程池为 10 的意思吗
    可能我没理解你的意思,“预先设定好线程池容量为 50”是要做什么?
    ClericPy
        2
    ClericPy  
       2020-03-20 23:10:16 +08:00   ❤️ 1
    https://docs.python.org/zh-cn/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor

    看看 Future 是个什么设计会帮助了解很多

    当然老版本的 from multiprocessing.dummy import Pool 也依然可以用
    ClericPy
        3
    ClericPy  
       2020-03-20 23:11:08 +08:00
    如果非要自己实现, Semphore 的用途应该就是限定并发用的, 用法和别的锁差不多
    lithbitren
        4
    lithbitren  
       2020-03-21 00:19:10 +08:00
    搞一个定容的 queue 队列,get 拿任务推到工厂也可以。
    524758861
        5
    524758861  
       2020-03-21 03:22:35 +08:00
    1.Executors.newFixedThreadPool(10)建立线程池,然后把任务 submit 进去 Callable,然后等待 10 个都执行完,需要 Future 的 get 去阻塞到全部执行完毕
    2.Executors.newFixedThreadPool(10)建立线程池,把任务全部 submit 进去 Runable,会自动替补的
    mlyy
        6
    mlyy  
       2020-03-21 06:42:27 +08:00 via iPhone
    lqw3030
        7
    lqw3030  
       2020-03-21 10:13:00 +08:00
    为什么要重复的启动线程呢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3757 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 04:33 · PVG 12:33 · LAX 21:33 · JFK 00:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.