用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
>>> 

 

转载于:https://www.cnblogs.com/onelang/p/10076190.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值