zoukankan      html  css  js  c++  java
  • 用Queue控制python多线程并发数量

    python多线程如果不进行并发数量控制,在启动线程数量多到一定程度后,会造成线程无法启动的错误。

    下面介绍用Queue控制多线程并发数量的方法(python3).

    # -*- coding: utf-8 -*-
    import threading
    import Queue
    import random
    import time
    
    maxThreads = 3
    
    class store(threading.Thread):
        def __init__(self, store, queue):
            threading.Thread.__init__(self)
            self.queue = queue
            self.store = store
    
        def run(self):
            try:
                time.sleep(random.randint(1,3))
                print('This is store %s' % self.store)
            except Exception as e:
                print(e)
            finally:
                self.queue.get()
                self.queue.task_done()
    
    def main():
        q = Queue.Queue(maxThreads)
        for s in range(15):
            q.put(s)
            t = store(s, q)
            t.start()
        q.join()
        print('over')
    
    if __name__ == '__main__':
        main()
    This is store 1
    This is store 3
    This is store 0
    This is store 2
    This is store 4
    This is store 6
    This is store 5
    This is store 7
    This is store 8
    This is store 9
    This is store 11
    This is store 13
    This is store 10
    This is store 12
    This is store 14
    over
    >>> 
    技术不行 业务不行 管理不行
  • 相关阅读:
    知识【inline】
    .net实现文件或目录复制到指定目录 及 压缩
    asp实现页面打印功能
    C#创建Windows服务(附服务安装)
    导出合并行及合并列
    Abp添加DBContext
    Background Jobs 调用接口时间长解决
    DataTable去掉空行
    Maven配置
    二维码q
  • 原文地址:https://www.cnblogs.com/onelang/p/10076190.html
Copyright © 2011-2022 走看看